file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public ownerAddress; 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 { ownerAddress = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == ownerAddress); _; } /** * @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(ownerAddress, newOwner); ownerAddress = 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title SafeMath32 * @dev SafeMath library implemented for uint32 */ library SafeMath32 { function mul(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } function div(uint32 a, uint32 b) internal pure returns (uint32) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint32 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint32 a, uint32 b) internal pure returns (uint32) { assert(b <= a); return a - b; } function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } /** * @title SafeMath16 * @dev SafeMath library implemented for uint16 */ library SafeMath16 { function mul(uint16 a, uint16 b) internal pure returns (uint16) { if (a == 0) { return 0; } uint16 c = a * b; assert(c / a == b); return c; } function div(uint16 a, uint16 b) internal pure returns (uint16) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint16 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } function add(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } contract Solethium is Ownable, ERC721 { uint16 private devCutPromille = 25; /** ** @dev EVENTS **/ event EventSolethiumObjectCreated(uint256 tokenId, string name); event EventSolethiumObjectBought(address oldOwner, address newOwner, uint price); // @dev use SafeMath for the following uints using SafeMath for uint256; // 1,15792E+77 using SafeMath for uint32; // 4294967296 using SafeMath for uint16; // 65536 // @dev an object - CrySolObject ( dev expression for Solethium Object)- contains relevant attributes only struct CrySolObject { string name; uint256 price; uint256 id; uint16 parentID; uint16 percentWhenParent; address owner; uint8 specialPropertyType; // 0=NONE, 1=PARENT_UP uint8 specialPropertyValue; // example: 5 meaning 0,5 % } // @dev an array of all CrySolObject objects in the game CrySolObject[] public crySolObjects; // @dev integer - total number of CrySol Objects uint16 public numberOfCrySolObjects; // @dev Total number of CrySol ETH worth in the game uint256 public ETHOfCrySolObjects; mapping (address => uint) public ownerCrySolObjectsCount; // for owner address, track number on tokens owned mapping (address => uint) public ownerAddPercentToParent; // adding additional percents to owners of some Objects when they have PARENT objects mapping (address => string) public ownerToNickname; // for owner address, track his nickname /** ** @dev MODIFIERS **/ modifier onlyOwnerOf(uint _id) { require(msg.sender == crySolObjects[_id].owner); _; } /** ** @dev NEXT PRICE CALCULATIONS **/ uint256 private nextPriceTreshold1 = 0.05 ether; uint256 private nextPriceTreshold2 = 0.3 ether; uint256 private nextPriceTreshold3 = 1.0 ether; uint256 private nextPriceTreshold4 = 5.0 ether; uint256 private nextPriceTreshold5 = 10.0 ether; function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price <= nextPriceTreshold1) { return _price.mul(200).div(100); } else if (_price <= nextPriceTreshold2) { return _price.mul(170).div(100); } else if (_price <= nextPriceTreshold3) { return _price.mul(150).div(100); } else if (_price <= nextPriceTreshold4) { return _price.mul(140).div(100); } else if (_price <= nextPriceTreshold5) { return _price.mul(130).div(100); } else { return _price.mul(120).div(100); } } /** ** @dev this method is used to create CrySol Object **/ function createCrySolObject(string _name, uint _price, uint16 _parentID, uint16 _percentWhenParent, uint8 _specialPropertyType, uint8 _specialPropertyValue) external onlyOwner() { uint256 _id = crySolObjects.length; crySolObjects.push(CrySolObject(_name, _price, _id, _parentID, _percentWhenParent, msg.sender, _specialPropertyType, _specialPropertyValue)) ; //insert into array ownerCrySolObjectsCount[msg.sender] = ownerCrySolObjectsCount[msg.sender].add(1); // increase count for OWNER numberOfCrySolObjects = (uint16)(numberOfCrySolObjects.add(1)); // increase count for Total number ETHOfCrySolObjects = ETHOfCrySolObjects.add(_price); // increase total ETH worth of all tokens EventSolethiumObjectCreated(_id, _name); } /** ** @dev this method is used to GET CrySol Objects from one OWNER **/ function getCrySolObjectsByOwner(address _owner) external view returns(uint[]) { uint256 tokenCount = ownerCrySolObjectsCount[_owner]; if (tokenCount == 0) { return new uint256[](0); } else { uint[] memory result = new uint[](tokenCount); uint counter = 0; for (uint i = 0; i < numberOfCrySolObjects; i++) { if (crySolObjects[i].owner == _owner) { result[counter] = i; counter++; } } return result; } } /** ** @dev this method is used to GET ALL CrySol Objects in the game **/ function getAllCrySolObjects() external view returns(uint[]) { uint[] memory result = new uint[](numberOfCrySolObjects); uint counter = 0; for (uint i = 0; i < numberOfCrySolObjects; i++) { result[counter] = i; counter++; } return result; } /** ** @dev this method is used to calculate Developer's Cut in the game **/ function returnDevelopersCut(uint256 _price) private view returns(uint) { return _price.mul(devCutPromille).div(1000); } /** ** @dev this method is used to calculate Parent Object's Owner Cut in the game ** owner of PARENT objects will get : percentWhenParent % from his Objects + any additional bonuses he may have from SPECIAL trade objects ** that are increasing PARENT percentage **/ function returnParentObjectCut( CrySolObject storage _obj, uint256 _price ) private view returns(uint) { uint256 _percentWhenParent = crySolObjects[_obj.parentID].percentWhenParent + (ownerAddPercentToParent[crySolObjects[_obj.parentID].owner]).div(10); return _price.mul(_percentWhenParent).div(100); //_parentCut } /** ** @dev this method is used to TRANSFER OWNERSHIP of the CrySol Objects in the game on the BUY event **/ function _transferOwnershipOnBuy(address _oldOwner, uint _id, address _newOwner) private { // decrease count for original OWNER ownerCrySolObjectsCount[_oldOwner] = ownerCrySolObjectsCount[_oldOwner].sub(1); // new owner gets ownership crySolObjects[_id].owner = _newOwner; ownerCrySolObjectsCount[_newOwner] = ownerCrySolObjectsCount[_newOwner].add(1); // increase count for the new OWNER ETHOfCrySolObjects = ETHOfCrySolObjects.sub(crySolObjects[_id].price); crySolObjects[_id].price = calculateNextPrice(crySolObjects[_id].price); // now, calculate and update next price ETHOfCrySolObjects = ETHOfCrySolObjects.add(crySolObjects[_id].price); } /** ** @dev this method is used to BUY CrySol Objects in the game, defining what will happen with the next price **/ function buyCrySolObject(uint _id) external payable { CrySolObject storage _obj = crySolObjects[_id]; uint256 price = _obj.price; address oldOwner = _obj.owner; // seller address newOwner = msg.sender; // buyer require(msg.value >= price); require(msg.sender != _obj.owner); // can't buy again the same thing! uint256 excess = msg.value.sub(price); // calculate if percentage will go to parent Object owner crySolObjects[_obj.parentID].owner.transfer(returnParentObjectCut(_obj, price)); // Transfer payment to old owner minus the developer's cut, parent owner's cut and any special Object's cut. uint256 _oldOwnerCut = 0; _oldOwnerCut = price.sub(returnDevelopersCut(price)); _oldOwnerCut = _oldOwnerCut.sub(returnParentObjectCut(_obj, price)); oldOwner.transfer(_oldOwnerCut); // if there was excess in payment, return that to newOwner buying Object! if (excess > 0) { newOwner.transfer(excess); } //if the sell object has special property, we have to update ownerAddPercentToParent for owners addresses // 0=NONE, 1=PARENT_UP if (_obj.specialPropertyType == 1) { if (oldOwner != ownerAddress) { ownerAddPercentToParent[oldOwner] = ownerAddPercentToParent[oldOwner].sub(_obj.specialPropertyValue); } ownerAddPercentToParent[newOwner] = ownerAddPercentToParent[newOwner].add(_obj.specialPropertyValue); } _transferOwnershipOnBuy(oldOwner, _id, newOwner); // fire event EventSolethiumObjectBought(oldOwner, newOwner, price); } /** ** @dev this method is used to SET user's nickname **/ function setOwnerNickName(address _owner, string _nickName) external { require(msg.sender == _owner); ownerToNickname[_owner] = _nickName; // set nickname } /** ** @dev this method is used to GET user's nickname **/ function getOwnerNickName(address _owner) external view returns(string) { return ownerToNickname[_owner]; } /** ** @dev some helper / info getter functions **/ function getContractOwner() external view returns(address) { return ownerAddress; } function getBalance() external view returns(uint) { return this.balance; } function getNumberOfCrySolObjects() external view returns(uint16) { return numberOfCrySolObjects; } /* @dev Withdraw All or part of contract balance to Contract Owner address */ function withdrawAll() onlyOwner() public { ownerAddress.transfer(this.balance); } function withdrawAmount(uint256 _amount) onlyOwner() public { ownerAddress.transfer(_amount); } /** ** @dev this method is used to modify parentID if needed later; ** For this game it is very important to keep intended hierarchy; you never know WHEN exactly transaction will be confirmed in the blockchain ** Every Object creation is transaction; if by some accident Objects get "wrong" ID in the crySolObjects array, this is the method where we can adjust parentId ** for objects orbiting it (we don't want for Moon to end up orbiting Mars :) ) **/ function setParentID (uint _crySolObjectID, uint16 _parentID) external onlyOwner() { crySolObjects[_crySolObjectID].parentID = _parentID; } /** ** @dev ERC-721 compliant methods; ** Another contracts can simply talk to us without needing to know anything about our internal contract implementation **/ mapping (uint => address) crySolObjectsApprovals; event Transfer(address indexed _from, address indexed _to, uint256 _id); event Approval(address indexed _owner, address indexed _approved, uint256 _id); function name() public pure returns (string _name) { return "Solethium"; } function symbol() public pure returns (string _symbol) { return "SOL"; } function totalSupply() public view returns (uint256 _totalSupply) { return crySolObjects.length; } function balanceOf(address _owner) public view returns (uint256 _balance) { return ownerCrySolObjectsCount[_owner]; } function ownerOf(uint256 _id) public view returns (address _owner) { return crySolObjects[_id].owner; } function _transferHelper(address _from, address _to, uint256 _id) private { ownerCrySolObjectsCount[_to] = ownerCrySolObjectsCount[_to].add(1); ownerCrySolObjectsCount[_from] = ownerCrySolObjectsCount[_from].sub(1); crySolObjects[_id].owner = _to; Transfer(_from, _to, _id); // fire event } function transfer(address _to, uint256 _id) public onlyOwnerOf(_id) { _transferHelper(msg.sender, _to, _id); } function approve(address _to, uint256 _id) public onlyOwnerOf(_id) { require(msg.sender != _to); crySolObjectsApprovals[_id] = _to; Approval(msg.sender, _to, _id); // fire event } function takeOwnership(uint256 _id) public { require(crySolObjectsApprovals[_id] == msg.sender); _transferHelper(ownerOf(_id), msg.sender, _id); } }
* @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 ownerAddress; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { ownerAddress = msg.sender; } modifier onlyOwner() { require(msg.sender == ownerAddress); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(ownerAddress, newOwner); ownerAddress = newOwner; } }
5,782,739
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 288, 203, 225, 1758, 1071, 3410, 1887, 31, 203, 203, 225, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 225, 445, 14223, 6914, 1435, 1071, 288, 203, 565, 3410, 1887, 273, 1234, 18, 15330, 31, 203, 225, 289, 203, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 3410, 1887, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 565, 14223, 9646, 5310, 1429, 4193, 12, 8443, 1887, 16, 394, 5541, 1769, 203, 565, 3410, 1887, 273, 394, 5541, 31, 203, 225, 289, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x088D78D2025FB7BD52788F47cbDf385d247bDc76/sources/contracts/interfaces/IStakingRewards.sol
ERROR: type should be string, got " https:docs.synthetix.io/contracts/source/interfaces/istakingrewards Views Mutative"
interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function totalStaked() external view returns (uint256); function exit() external; function stake( uint256 amount, bytes32 root_, bytes32[] calldata proof_ ) external; function withdraw(uint256 amount) external; pragma solidity >=0.4.24; }
8,320,877
[ 1, 4528, 30, 8532, 18, 11982, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 15898, 19, 376, 6159, 266, 6397, 31117, 14138, 1535, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 510, 6159, 17631, 14727, 288, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 425, 1303, 329, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4170, 359, 1060, 1290, 5326, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 31323, 17631, 1060, 27873, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 19890, 2173, 1345, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 2078, 510, 9477, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 203, 565, 445, 2427, 1435, 3903, 31, 203, 203, 565, 445, 384, 911, 12, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 1578, 1365, 67, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 14601, 67, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 683, 9454, 18035, 560, 1545, 20, 18, 24, 18, 3247, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "../openzeppelin/ERC20.sol"; import "../openzeppelin/SafeERC20.sol"; import "../openzeppelin/SafeMath.sol"; import "./LiquidityMiningStorage.sol"; import "./ILiquidityMining.sol"; contract LiquidityMining is ILiquidityMining, LiquidityMiningStorage { using SafeMath for uint256; using SafeERC20 for IERC20; /* Constants */ uint256 public constant PRECISION = 1e12; // Bonus multiplier for early liquidity providers. // During bonus period each passed block will be calculated like N passed blocks, where N = BONUS_MULTIPLIER uint256 public constant BONUS_BLOCK_MULTIPLIER = 10; uint256 public constant SECONDS_PER_BLOCK = 30; /* Events */ event SOVTransferred(address indexed receiver, uint256 amount); event PoolTokenAdded(address indexed user, address indexed poolToken, uint256 allocationPoint); event PoolTokenUpdated( address indexed user, address indexed poolToken, uint256 newAllocationPoint, uint256 oldAllocationPoint ); event Deposit(address indexed user, address indexed poolToken, uint256 amount); event RewardClaimed(address indexed user, address indexed poolToken, uint256 amount); event Withdraw(address indexed user, address indexed poolToken, uint256 amount); event EmergencyWithdraw( address indexed user, address indexed poolToken, uint256 amount, uint256 accumulatedReward ); /* Functions */ /** * @notice Initialize mining. * * @param _SOV The SOV token. * @param _rewardTokensPerBlock The number of reward tokens per block. * @param _startDelayBlocks The number of blocks should be passed to start * mining. * @param _numberOfBonusBlocks The number of blocks when each block will * be calculated as N blocks (BONUS_BLOCK_MULTIPLIER). * @param _lockedSOV The contract instance address of the lockedSOV vault. * SOV rewards are not paid directly to liquidity providers. Instead they * are deposited into a lockedSOV vault contract. * @param _unlockedImmediatelyPercent The % which determines how much will be unlocked immediately. */ function initialize( IERC20 _SOV, uint256 _rewardTokensPerBlock, uint256 _startDelayBlocks, uint256 _numberOfBonusBlocks, address _wrapper, ILockedSOV _lockedSOV, uint256 _unlockedImmediatelyPercent ) external onlyAuthorized { /// @dev Non-idempotent function. Must be called just once. require(address(SOV) == address(0), "Already initialized"); require(address(_SOV) != address(0), "Invalid token address"); require(_startDelayBlocks > 0, "Invalid start block"); require( _unlockedImmediatelyPercent < 10000, "Unlocked immediately percent has to be less than 10000." ); SOV = _SOV; rewardTokensPerBlock = _rewardTokensPerBlock; startBlock = block.number + _startDelayBlocks; bonusEndBlock = startBlock + _numberOfBonusBlocks; wrapper = _wrapper; lockedSOV = _lockedSOV; unlockedImmediatelyPercent = _unlockedImmediatelyPercent; } /** * @notice Sets lockedSOV contract. * @param _lockedSOV The contract instance address of the lockedSOV vault. */ function setLockedSOV(ILockedSOV _lockedSOV) external onlyAuthorized { require(address(_lockedSOV) != address(0), "Invalid lockedSOV Address."); lockedSOV = _lockedSOV; } /** * @notice Sets unlocked immediately percent. * @param _unlockedImmediatelyPercent The % which determines how much will be unlocked immediately. * @dev @dev 10000 is 100% */ function setUnlockedImmediatelyPercent(uint256 _unlockedImmediatelyPercent) external onlyAuthorized { require( _unlockedImmediatelyPercent < 10000, "Unlocked immediately percent has to be less than 10000." ); unlockedImmediatelyPercent = _unlockedImmediatelyPercent; } /** * @notice sets wrapper proxy contract * @dev can be set to zero address to remove wrapper */ function setWrapper(address _wrapper) external onlyAuthorized { wrapper = _wrapper; } /** * @notice stops mining by setting end block */ function stopMining() external onlyAuthorized { require(endBlock == 0, "Already stopped"); endBlock = block.number; } /** * @notice Transfers SOV tokens to given address. * Owner use this function to withdraw SOV from LM contract * into another account. * @param _receiver The address of the SOV receiver. * @param _amount The amount to be transferred. * */ function transferSOV(address _receiver, uint256 _amount) external onlyAuthorized { require(_receiver != address(0), "Receiver address invalid"); require(_amount != 0, "Amount invalid"); /// @dev Do not transfer more SOV than available. uint256 SOVBal = SOV.balanceOf(address(this)); if (_amount > SOVBal) { _amount = SOVBal; } /// @dev The actual transfer. require(SOV.transfer(_receiver, _amount), "Transfer failed"); /// @dev Event log. emit SOVTransferred(_receiver, _amount); } /** * @notice Get the missed SOV balance of LM contract. * * @return The amount of SOV tokens according to totalUsersBalance * in excess of actual SOV balance of the LM contract. * */ function getMissedBalance() external view returns (uint256) { uint256 balance = SOV.balanceOf(address(this)); return balance >= totalUsersBalance ? 0 : totalUsersBalance.sub(balance); } /** * @notice adds a new lp to the pool. Can only be called by the owner or an admin * @param _poolToken the address of pool token * @param _allocationPoint the allocation point (weight) for the given pool * @param _withUpdate the flag whether we need to update all pools */ function add( address _poolToken, uint96 _allocationPoint, bool _withUpdate ) external onlyAuthorized { require(_allocationPoint > 0, "Invalid allocation point"); require(_poolToken != address(0), "Invalid token address"); require(poolIdList[_poolToken] == 0, "Token already added"); if (_withUpdate) { updateAllPools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocationPoint = totalAllocationPoint.add(_allocationPoint); poolInfoList.push( PoolInfo({ poolToken: IERC20(_poolToken), allocationPoint: _allocationPoint, lastRewardBlock: lastRewardBlock, accumulatedRewardPerShare: 0 }) ); //indexing starts from 1 in order to check whether token was already added poolIdList[_poolToken] = poolInfoList.length; emit PoolTokenAdded(msg.sender, _poolToken, _allocationPoint); } /** * @notice updates the given pool's reward tokens allocation point * @param _poolToken the address of pool token * @param _allocationPoint the allocation point (weight) for the given pool * @param _updateAllFlag the flag whether we need to update all pools */ function update( address _poolToken, uint96 _allocationPoint, bool _updateAllFlag ) external onlyAuthorized { if (_updateAllFlag) { updateAllPools(); } else { updatePool(_poolToken); } _updateToken(_poolToken, _allocationPoint); } function _updateToken(address _poolToken, uint96 _allocationPoint) internal { uint256 poolId = _getPoolId(_poolToken); uint256 previousAllocationPoint = poolInfoList[poolId].allocationPoint; totalAllocationPoint = totalAllocationPoint.sub(previousAllocationPoint).add( _allocationPoint ); poolInfoList[poolId].allocationPoint = _allocationPoint; emit PoolTokenUpdated(msg.sender, _poolToken, _allocationPoint, previousAllocationPoint); } /** * @notice updates the given pools' reward tokens allocation points * @param _poolTokens array of addresses of pool tokens * @param _allocationPoints array of allocation points (weight) for the given pools * @param _updateAllFlag the flag whether we need to update all pools */ function updateTokens( address[] calldata _poolTokens, uint96[] calldata _allocationPoints, bool _updateAllFlag ) external onlyAuthorized { require(_poolTokens.length == _allocationPoints.length, "Arrays mismatch"); if (_updateAllFlag) { updateAllPools(); } uint256 length = _poolTokens.length; for (uint256 i = 0; i < length; i++) { if (!_updateAllFlag) { updatePool(_poolTokens[i]); } _updateToken(_poolTokens[i], _allocationPoints[i]); } } /** * @notice returns reward multiplier over the given _from to _to block * @param _from the first block for a calculation * @param _to the last block for a calculation */ function _getPassedBlocksWithBonusMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_from < startBlock) { _from = startBlock; } if (endBlock > 0 && _to > endBlock) { _to = endBlock; } if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_BLOCK_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_BLOCK_MULTIPLIER).add(_to.sub(bonusEndBlock)); } } function _getUserAccumulatedReward(uint256 _poolId, address _user) internal view returns (uint256) { PoolInfo storage pool = poolInfoList[_poolId]; UserInfo storage user = userInfoMap[_poolId][_user]; uint256 accumulatedRewardPerShare = pool.accumulatedRewardPerShare; uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && poolTokenBalance != 0) { (, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool); accumulatedRewardPerShare = accumulatedRewardPerShare.add(accumulatedRewardPerShare_); } return user.amount.mul(accumulatedRewardPerShare).div(PRECISION).sub(user.rewardDebt); } /** * @notice returns accumulated reward * @param _poolToken the address of pool token * @param _user the user address */ function getUserAccumulatedReward(address _poolToken, address _user) external view returns (uint256) { uint256 poolId = _getPoolId(_poolToken); return _getUserAccumulatedReward(poolId, _user); } /** * @notice returns estimated reward * @param _poolToken the address of pool token * @param _amount the amount of tokens to be deposited * @param _duration the duration of liquidity providing in seconds */ function getEstimatedReward( address _poolToken, uint256 _amount, uint256 _duration ) external view returns (uint256) { uint256 poolId = _getPoolId(_poolToken); PoolInfo storage pool = poolInfoList[poolId]; uint256 start = block.number; uint256 end = start.add(_duration.div(SECONDS_PER_BLOCK)); (, uint256 accumulatedRewardPerShare) = _getPoolAccumulatedReward(pool, _amount, start, end); return _amount.mul(accumulatedRewardPerShare).div(PRECISION); } /** * @notice Updates reward variables for all pools. * @dev Be careful of gas spending! */ function updateAllPools() public { uint256 length = poolInfoList.length; for (uint256 i = 0; i < length; i++) { _updatePool(i); } } /** * @notice Updates reward variables of the given pool to be up-to-date * @param _poolToken the address of pool token */ function updatePool(address _poolToken) public { uint256 poolId = _getPoolId(_poolToken); _updatePool(poolId); } function _updatePool(uint256 _poolId) internal { PoolInfo storage pool = poolInfoList[_poolId]; //this pool has been updated recently if (block.number <= pool.lastRewardBlock) { return; } uint256 poolTokenBalance = pool.poolToken.balanceOf(address(this)); if (poolTokenBalance == 0) { pool.lastRewardBlock = block.number; return; } (uint256 accumulatedReward_, uint256 accumulatedRewardPerShare_) = _getPoolAccumulatedReward(pool); pool.accumulatedRewardPerShare = pool.accumulatedRewardPerShare.add( accumulatedRewardPerShare_ ); pool.lastRewardBlock = block.number; totalUsersBalance = totalUsersBalance.add(accumulatedReward_); } function _getPoolAccumulatedReward(PoolInfo storage _pool) internal view returns (uint256, uint256) { return _getPoolAccumulatedReward(_pool, 0, _pool.lastRewardBlock, block.number); } function _getPoolAccumulatedReward( PoolInfo storage _pool, uint256 _additionalAmount, uint256 _startBlock, uint256 _endBlock ) internal view returns (uint256, uint256) { uint256 passedBlocks = _getPassedBlocksWithBonusMultiplier(_startBlock, _endBlock); uint256 accumulatedReward = passedBlocks.mul(rewardTokensPerBlock).mul(_pool.allocationPoint).div( totalAllocationPoint ); uint256 poolTokenBalance = _pool.poolToken.balanceOf(address(this)); poolTokenBalance = poolTokenBalance.add(_additionalAmount); uint256 accumulatedRewardPerShare = accumulatedReward.mul(PRECISION).div(poolTokenBalance); return (accumulatedReward, accumulatedRewardPerShare); } /** * @notice deposits pool tokens * @param _poolToken the address of pool token * @param _amount the amount of pool tokens * @param _user the address of user, tokens will be deposited to it or to msg.sender */ function deposit( address _poolToken, uint256 _amount, address _user ) external { _deposit(_poolToken, _amount, _user, false); } /** * @notice if the lending pools directly mint/transfer tokens to this address, process it like a user deposit * @dev only callable by the pool which issues the tokens * @param _user the user address * @param _amount the minted amount */ function onTokensDeposited(address _user, uint256 _amount) external { //the msg.sender is the pool token. if the msg.sender is not a valid pool token, _deposit will revert _deposit(msg.sender, _amount, _user, true); } /** * @notice internal function for depositing pool tokens * @param _poolToken the address of pool token * @param _amount the amount of pool tokens * @param _user the address of user, tokens will be deposited to it * @param alreadyTransferred true if the pool tokens have already been transferred */ function _deposit( address _poolToken, uint256 _amount, address _user, bool alreadyTransferred ) internal { require(poolIdList[_poolToken] != 0, "Pool token not found"); address userAddress = _user != address(0) ? _user : msg.sender; uint256 poolId = _getPoolId(_poolToken); PoolInfo storage pool = poolInfoList[poolId]; UserInfo storage user = userInfoMap[poolId][userAddress]; _updatePool(poolId); //sends reward directly to the user _updateReward(pool, user); if (_amount > 0) { //receives pool tokens from msg.sender, it can be user or WrapperProxy contract if (!alreadyTransferred) pool.poolToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } _updateRewardDebt(pool, user); emit Deposit(userAddress, _poolToken, _amount); } /** * @notice transfers reward tokens * @param _poolToken the address of pool token * @param _user the address of user to claim reward from (can be passed only by wrapper contract) */ function claimReward(address _poolToken, address _user) external { address userAddress = _getUserAddress(_user); uint256 poolId = _getPoolId(_poolToken); _claimReward(poolId, userAddress, true); } function _claimReward( uint256 _poolId, address _userAddress, bool _isStakingTokens ) internal { PoolInfo storage pool = poolInfoList[_poolId]; UserInfo storage user = userInfoMap[_poolId][_userAddress]; _updatePool(_poolId); _updateReward(pool, user); _transferReward(address(pool.poolToken), user, _userAddress, _isStakingTokens, true); _updateRewardDebt(pool, user); } /** * @notice transfers reward tokens from all pools * @param _user the address of user to claim reward from (can be passed only by wrapper contract) */ function claimRewardFromAllPools(address _user) external { address userAddress = _getUserAddress(_user); uint256 length = poolInfoList.length; for (uint256 i = 0; i < length; i++) { uint256 poolId = i; _claimReward(poolId, userAddress, false); } lockedSOV.withdrawAndStakeTokensFrom(userAddress); } /** * @notice withdraws pool tokens and transfers reward tokens * @param _poolToken the address of pool token * @param _amount the amount of pool tokens * @param _user the user address will be used to process a withdrawal (can be passed only by wrapper contract) */ function withdraw( address _poolToken, uint256 _amount, address _user ) external { require(poolIdList[_poolToken] != 0, "Pool token not found"); address userAddress = _getUserAddress(_user); uint256 poolId = _getPoolId(_poolToken); PoolInfo storage pool = poolInfoList[poolId]; UserInfo storage user = userInfoMap[poolId][userAddress]; require(user.amount >= _amount, "Not enough balance"); _updatePool(poolId); _updateReward(pool, user); _transferReward(_poolToken, user, userAddress, false, false); user.amount = user.amount.sub(_amount); //msg.sender is wrapper -> send to wrapper if (msg.sender == wrapper) { pool.poolToken.safeTransfer(address(msg.sender), _amount); } //msg.sender is user or pool token (lending pool) -> send to user else { pool.poolToken.safeTransfer(userAddress, _amount); } _updateRewardDebt(pool, user); emit Withdraw(userAddress, _poolToken, _amount); } function _getUserAddress(address _user) internal view returns (address) { address userAddress = msg.sender; if (_user != address(0)) { //only wrapper can pass _user parameter require( msg.sender == wrapper || poolIdList[msg.sender] != 0, "only wrapper or pools may withdraw for a user" ); userAddress = _user; } return userAddress; } function _updateReward(PoolInfo storage pool, UserInfo storage user) internal { //update user accumulated reward if (user.amount > 0) { //add reward for the previous amount of deposited tokens uint256 accumulatedReward = user.amount.mul(pool.accumulatedRewardPerShare).div(PRECISION).sub( user.rewardDebt ); user.accumulatedReward = user.accumulatedReward.add(accumulatedReward); } } function _updateRewardDebt(PoolInfo storage pool, UserInfo storage user) internal { //reward accumulated before amount update (should be subtracted during next reward calculation) user.rewardDebt = user.amount.mul(pool.accumulatedRewardPerShare).div(PRECISION); } /** * @notice Send reward in SOV to the lockedSOV vault. * @param _user The user info, to get its reward share. * @param _userAddress The address of the user, to send SOV in its behalf. * @param _isStakingTokens The flag whether we need to stake tokens * @param _isCheckingBalance The flag whether we need to throw error or don't process reward if SOV balance isn't enough */ function _transferReward( address _poolToken, UserInfo storage _user, address _userAddress, bool _isStakingTokens, bool _isCheckingBalance ) internal { uint256 userAccumulatedReward = _user.accumulatedReward; /// @dev Transfer if enough SOV balance on this LM contract. uint256 balance = SOV.balanceOf(address(this)); if (balance >= userAccumulatedReward) { totalUsersBalance = totalUsersBalance.sub(userAccumulatedReward); _user.accumulatedReward = 0; /// @dev Instead of transferring the reward to the LP (user), /// deposit it into lockedSOV vault contract, but first /// SOV deposit must be approved to move the SOV tokens /// from this LM contract into the lockedSOV vault. require(SOV.approve(address(lockedSOV), userAccumulatedReward), "Approve failed"); lockedSOV.deposit(_userAddress, userAccumulatedReward, unlockedImmediatelyPercent); if (_isStakingTokens) { lockedSOV.withdrawAndStakeTokensFrom(_userAddress); } /// @dev Event log. emit RewardClaimed(_userAddress, _poolToken, userAccumulatedReward); } else { require(!_isCheckingBalance, "Claiming reward failed"); } } /** * @notice withdraws pool tokens without transferring reward tokens * @param _poolToken the address of pool token * @dev EMERGENCY ONLY */ function emergencyWithdraw(address _poolToken) external { uint256 poolId = _getPoolId(_poolToken); PoolInfo storage pool = poolInfoList[poolId]; UserInfo storage user = userInfoMap[poolId][msg.sender]; _updatePool(poolId); _updateReward(pool, user); totalUsersBalance = totalUsersBalance.sub(user.accumulatedReward); uint256 userAmount = user.amount; uint256 userAccumulatedReward = user.accumulatedReward; user.amount = 0; user.rewardDebt = 0; user.accumulatedReward = 0; pool.poolToken.safeTransfer(address(msg.sender), userAmount); _updateRewardDebt(pool, user); emit EmergencyWithdraw(msg.sender, _poolToken, userAmount, userAccumulatedReward); } /** * @notice returns pool id * @param _poolToken the address of pool token */ function getPoolId(address _poolToken) external view returns (uint256) { return _getPoolId(_poolToken); } function _getPoolId(address _poolToken) internal view returns (uint256) { uint256 poolId = poolIdList[_poolToken]; require(poolId > 0, "Pool token not found"); return poolId - 1; } /** * @notice returns count of pool tokens */ function getPoolLength() external view returns (uint256) { return poolInfoList.length; } /** * @notice returns list of pool token's info */ function getPoolInfoList() external view returns (PoolInfo[] memory) { return poolInfoList; } /** * @notice returns pool info for the given token * @param _poolToken the address of pool token */ function getPoolInfo(address _poolToken) external view returns (PoolInfo memory) { uint256 poolId = _getPoolId(_poolToken); return poolInfoList[poolId]; } /** * @notice returns list of [amount, accumulatedReward] for the given user for each pool token * @param _user the address of the user */ function getUserBalanceList(address _user) external view returns (uint256[2][] memory) { uint256 length = poolInfoList.length; uint256[2][] memory userBalanceList = new uint256[2][](length); for (uint256 i = 0; i < length; i++) { userBalanceList[i][0] = userInfoMap[i][_user].amount; userBalanceList[i][1] = _getUserAccumulatedReward(i, _user); } return userBalanceList; } /** * @notice returns UserInfo for the given pool and user * @param _poolToken the address of pool token * @param _user the address of the user */ function getUserInfo(address _poolToken, address _user) public view returns (UserInfo memory) { uint256 poolId = _getPoolId(_poolToken); return userInfoMap[poolId][_user]; } /** * @notice returns list of UserInfo for the given user for each pool token * @param _user the address of the user */ function getUserInfoList(address _user) external view returns (UserInfo[] memory) { uint256 length = poolInfoList.length; UserInfo[] memory userInfoList = new UserInfo[](length); for (uint256 i = 0; i < length; i++) { userInfoList[i] = userInfoMap[i][_user]; } return userInfoList; } /** * @notice returns accumulated reward for the given user for each pool token * @param _user the address of the user */ function getUserAccumulatedRewardList(address _user) external view returns (uint256[] memory) { uint256 length = poolInfoList.length; uint256[] memory rewardList = new uint256[](length); for (uint256 i = 0; i < length; i++) { rewardList[i] = _getUserAccumulatedReward(i, _user); } return rewardList; } /** * @notice returns the pool token balance a user has on the contract * @param _poolToken the address of pool token * @param _user the address of the user */ function getUserPoolTokenBalance(address _poolToken, address _user) external view returns (uint256) { UserInfo memory ui = getUserInfo(_poolToken, _user); return ui.amount; } }
* @notice Send reward in SOV to the lockedSOV vault. @param _user The user info, to get its reward share. @param _userAddress The address of the user, to send SOV in its behalf. @param _isStakingTokens The flag whether we need to stake tokens @param _isCheckingBalance The flag whether we need to throw error or don't process reward if SOV balance isn't enough/ @dev Transfer if enough SOV balance on this LM contract. @dev Instead of transferring the reward to the LP (user), deposit it into lockedSOV vault contract, but first SOV deposit must be approved to move the SOV tokens from this LM contract into the lockedSOV vault.
function _transferReward( address _poolToken, UserInfo storage _user, address _userAddress, bool _isStakingTokens, bool _isCheckingBalance ) internal { uint256 userAccumulatedReward = _user.accumulatedReward; uint256 balance = SOV.balanceOf(address(this)); if (balance >= userAccumulatedReward) { totalUsersBalance = totalUsersBalance.sub(userAccumulatedReward); _user.accumulatedReward = 0; require(SOV.approve(address(lockedSOV), userAccumulatedReward), "Approve failed"); lockedSOV.deposit(_userAddress, userAccumulatedReward, unlockedImmediatelyPercent); if (_isStakingTokens) { lockedSOV.withdrawAndStakeTokensFrom(_userAddress); } require(!_isCheckingBalance, "Claiming reward failed"); } }
6,391,017
[ 1, 3826, 19890, 316, 7460, 58, 358, 326, 8586, 3584, 58, 9229, 18, 225, 389, 1355, 1021, 729, 1123, 16, 358, 336, 2097, 19890, 7433, 18, 225, 389, 1355, 1887, 1021, 1758, 434, 326, 729, 16, 358, 1366, 7460, 58, 316, 2097, 12433, 6186, 18, 225, 389, 291, 510, 6159, 5157, 1021, 2982, 2856, 732, 1608, 358, 384, 911, 2430, 225, 389, 291, 14294, 13937, 1021, 2982, 2856, 732, 1608, 358, 604, 555, 578, 2727, 1404, 1207, 19890, 309, 7460, 58, 11013, 5177, 1404, 7304, 19, 225, 12279, 309, 7304, 7460, 58, 11013, 603, 333, 511, 49, 6835, 18, 225, 17561, 434, 906, 74, 20245, 326, 19890, 358, 326, 511, 52, 261, 1355, 3631, 282, 443, 1724, 518, 1368, 8586, 3584, 58, 9229, 6835, 16, 1496, 1122, 282, 7460, 58, 443, 1724, 1297, 506, 20412, 358, 3635, 326, 7460, 58, 2430, 282, 628, 333, 511, 49, 6835, 1368, 326, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 13866, 17631, 1060, 12, 203, 3639, 1758, 389, 6011, 1345, 16, 203, 3639, 25003, 2502, 389, 1355, 16, 203, 3639, 1758, 389, 1355, 1887, 16, 203, 3639, 1426, 389, 291, 510, 6159, 5157, 16, 203, 3639, 1426, 389, 291, 14294, 13937, 203, 565, 262, 2713, 288, 203, 3639, 2254, 5034, 729, 8973, 5283, 690, 17631, 1060, 273, 389, 1355, 18, 8981, 5283, 690, 17631, 1060, 31, 203, 203, 3639, 2254, 5034, 11013, 273, 7460, 58, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 12296, 1545, 729, 8973, 5283, 690, 17631, 1060, 13, 288, 203, 5411, 2078, 6588, 13937, 273, 2078, 6588, 13937, 18, 1717, 12, 1355, 8973, 5283, 690, 17631, 1060, 1769, 203, 5411, 389, 1355, 18, 8981, 5283, 690, 17631, 1060, 273, 374, 31, 203, 203, 5411, 2583, 12, 3584, 58, 18, 12908, 537, 12, 2867, 12, 15091, 3584, 58, 3631, 729, 8973, 5283, 690, 17631, 1060, 3631, 315, 12053, 537, 2535, 8863, 203, 5411, 8586, 3584, 58, 18, 323, 1724, 24899, 1355, 1887, 16, 729, 8973, 5283, 690, 17631, 1060, 16, 25966, 1170, 7101, 8410, 1769, 203, 203, 5411, 309, 261, 67, 291, 510, 6159, 5157, 13, 288, 203, 7734, 8586, 3584, 58, 18, 1918, 9446, 1876, 510, 911, 5157, 1265, 24899, 1355, 1887, 1769, 203, 5411, 289, 203, 203, 5411, 2583, 12, 5, 67, 291, 14294, 13937, 16, 315, 9762, 310, 19890, 2535, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT import "../libraries/math/SafeMath.sol"; import "./interfaces/ISecondaryPriceFeed.sol"; import "./interfaces/IFastPriceEvents.sol"; import "../access/Governable.sol"; pragma solidity 0.6.12; contract FastPriceFeed is ISecondaryPriceFeed, Governable { using SafeMath for uint256; uint256 public constant PRICE_PRECISION = 10 ** 30; // uint256(~0) is 256 bits of 1s // shift the 1s by (256 - 32) to get (256 - 32) 0s followed by 32 1s uint256 constant public PRICE_BITMASK = uint256(~0) >> (256 - 32); bool public isInitialized; bool public isSpreadEnabled = false; address public fastPriceEvents; address public admin; address public tokenManager; uint256 public constant BASIS_POINTS_DIVISOR = 10000; uint256 public constant MAX_PRICE_DURATION = 30 minutes; uint256 public lastUpdatedAt; uint256 public lastUpdatedBlock; uint256 public priceDuration; uint256 public minBlockInterval; // volatility basis points uint256 public volBasisPoints; // max deviation from primary price uint256 public maxDeviationBasisPoints; mapping (address => uint256) public prices; uint256 public minAuthorizations; uint256 public disableFastPriceVoteCount = 0; mapping (address => bool) public isSigner; mapping (address => bool) public disableFastPriceVotes; // array of tokens used in setCompactedPrices, saves L1 calldata gas costs address[] public tokens; // array of tokenPrecisions used in setCompactedPrices, saves L1 calldata gas costs // if the token price will be sent with 3 decimals, then tokenPrecision for that token // should be 10 ** 3 uint256[] public tokenPrecisions; event DisableFastPrice(address signer); modifier onlySigner() { require(isSigner[msg.sender], "FastPriceFeed: forbidden"); _; } modifier onlyAdmin() { require(msg.sender == admin, "FastPriceFeed: forbidden"); _; } modifier onlyTokenManager() { require(msg.sender == tokenManager, "FastPriceFeed: forbidden"); _; } constructor( uint256 _priceDuration, uint256 _minBlockInterval, uint256 _maxDeviationBasisPoints, address _fastPriceEvents, address _admin, address _tokenManager ) public { require(_priceDuration <= MAX_PRICE_DURATION, "FastPriceFeed: invalid _priceDuration"); priceDuration = _priceDuration; minBlockInterval = _minBlockInterval; maxDeviationBasisPoints = _maxDeviationBasisPoints; fastPriceEvents = _fastPriceEvents; admin = _admin; tokenManager = _tokenManager; } function initialize(uint256 _minAuthorizations, address[] memory _signers) public onlyGov { require(!isInitialized, "FastPriceFeed: already initialized"); isInitialized = true; minAuthorizations = _minAuthorizations; for (uint256 i = 0; i < _signers.length; i++) { address signer = _signers[i]; isSigner[signer] = true; } } function setAdmin(address _admin) external onlyTokenManager { admin = _admin; } function setFastPriceEvents(address _fastPriceEvents) external onlyGov { fastPriceEvents = _fastPriceEvents; } function setPriceDuration(uint256 _priceDuration) external onlyGov { require(_priceDuration <= MAX_PRICE_DURATION, "FastPriceFeed: invalid _priceDuration"); priceDuration = _priceDuration; } function setIsSpreadEnabled(bool _isSpreadEnabled) external onlyGov { isSpreadEnabled = _isSpreadEnabled; } function setVolBasisPoints(uint256 _volBasisPoints) external onlyGov { volBasisPoints = _volBasisPoints; } function setTokens(address[] memory _tokens, uint256[] memory _tokenPrecisions) external onlyGov { require(_tokens.length == _tokenPrecisions.length, "FastPriceFeed: invalid lengths"); tokens = _tokens; tokenPrecisions = _tokenPrecisions; } function setPrices(address[] memory _tokens, uint256[] memory _prices) external onlyAdmin { setLastUpdatedAt(); for (uint256 i = 0; i < _tokens.length; i++) { address token = _tokens[i]; prices[token] = _prices[i]; if (fastPriceEvents != address(0)) { IFastPriceEvents(fastPriceEvents).emitPriceEvent(token, _prices[i]); } } } function setCompactedPrices(uint256[] memory _priceBitArray) external onlyAdmin { setLastUpdatedAt(); for (uint256 i = 0; i < _priceBitArray.length; i++) { uint256 priceBits = _priceBitArray[i]; for (uint256 j = 0; j < 8; j++) { uint256 index = i * 8 + j; if (index >= tokens.length) { return; } uint256 startBit = 32 * j; uint256 price = (priceBits >> startBit) & PRICE_BITMASK; address token = tokens[i * 8 + j]; uint256 tokenPrecision = tokenPrecisions[i * 8 + j]; uint256 adjustedPrice = price.mul(PRICE_PRECISION).div(tokenPrecision); prices[token] = adjustedPrice; if (fastPriceEvents != address(0)) { IFastPriceEvents(fastPriceEvents).emitPriceEvent(token, adjustedPrice); } } } } function disableFastPrice() external onlySigner { require(!disableFastPriceVotes[msg.sender], "FastPriceFeed: already voted"); disableFastPriceVotes[msg.sender] = true; disableFastPriceVoteCount = disableFastPriceVoteCount.add(1); emit DisableFastPrice(msg.sender); } function enableFastPrice() external onlySigner { require(disableFastPriceVotes[msg.sender], "FastPriceFeed: already enabled"); disableFastPriceVotes[msg.sender] = false; disableFastPriceVoteCount = disableFastPriceVoteCount.sub(1); } function favorFastPrice() public view returns (bool) { return (disableFastPriceVoteCount < minAuthorizations) && !isSpreadEnabled; } function getPrice(address _token, uint256 _refPrice, bool _maximise) external override view returns (uint256) { if (block.timestamp > lastUpdatedAt.add(priceDuration)) { return _refPrice; } uint256 fastPrice = prices[_token]; if (fastPrice == 0) { return _refPrice; } uint256 maxPrice = _refPrice.mul(BASIS_POINTS_DIVISOR.add(maxDeviationBasisPoints)).div(BASIS_POINTS_DIVISOR); uint256 minPrice = _refPrice.mul(BASIS_POINTS_DIVISOR.sub(maxDeviationBasisPoints)).div(BASIS_POINTS_DIVISOR); if (favorFastPrice()) { if (fastPrice >= minPrice && fastPrice <= maxPrice) { if (_maximise) { if (_refPrice > fastPrice) { uint256 volPrice = fastPrice.mul(BASIS_POINTS_DIVISOR.add(volBasisPoints)).div(BASIS_POINTS_DIVISOR); // the volPrice should not be more than _refPrice return volPrice > _refPrice ? _refPrice : volPrice; } return fastPrice; } if (_refPrice < fastPrice) { uint256 volPrice = fastPrice.mul(BASIS_POINTS_DIVISOR.sub(volBasisPoints)).div(BASIS_POINTS_DIVISOR); // the volPrice should not be less than _refPrice return volPrice < _refPrice ? _refPrice : volPrice; } return fastPrice; } } if (_maximise) { if (_refPrice > fastPrice) { return _refPrice; } return fastPrice > maxPrice ? maxPrice : fastPrice; } if (_refPrice < fastPrice) { return _refPrice; } return fastPrice < minPrice ? minPrice : fastPrice; } function setLastUpdatedAt() private { require(block.number.sub(lastUpdatedBlock) >= minBlockInterval, "FastPriceFeed: minBlockInterval not yet passed"); lastUpdatedAt = block.timestamp; lastUpdatedBlock = block.number; } }
the volPrice should not be more than _refPrice the volPrice should not be less than _refPrice
function getPrice(address _token, uint256 _refPrice, bool _maximise) external override view returns (uint256) { uint256 fastPrice = prices[_token]; uint256 maxPrice = _refPrice.mul(BASIS_POINTS_DIVISOR.add(maxDeviationBasisPoints)).div(BASIS_POINTS_DIVISOR); uint256 minPrice = _refPrice.mul(BASIS_POINTS_DIVISOR.sub(maxDeviationBasisPoints)).div(BASIS_POINTS_DIVISOR); if (favorFastPrice()) { if (fastPrice >= minPrice && fastPrice <= maxPrice) { if (_maximise) { if (_refPrice > fastPrice) { uint256 volPrice = fastPrice.mul(BASIS_POINTS_DIVISOR.add(volBasisPoints)).div(BASIS_POINTS_DIVISOR); return volPrice > _refPrice ? _refPrice : volPrice; } return fastPrice; } if (_refPrice < fastPrice) { uint256 volPrice = fastPrice.mul(BASIS_POINTS_DIVISOR.sub(volBasisPoints)).div(BASIS_POINTS_DIVISOR); return volPrice < _refPrice ? _refPrice : volPrice; } return fastPrice; } } if (_maximise) { return fastPrice > maxPrice ? maxPrice : fastPrice; } return fastPrice < minPrice ? minPrice : fastPrice; }
13,014,902
[ 1, 5787, 6626, 5147, 1410, 486, 506, 1898, 2353, 389, 1734, 5147, 326, 6626, 5147, 1410, 486, 506, 5242, 2353, 389, 1734, 5147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25930, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 1734, 5147, 16, 1426, 389, 1896, 381, 784, 13, 3903, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 203, 3639, 2254, 5034, 4797, 5147, 273, 19827, 63, 67, 2316, 15533, 203, 203, 3639, 2254, 5034, 943, 5147, 273, 389, 1734, 5147, 18, 16411, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 18, 1289, 12, 1896, 758, 13243, 11494, 291, 5636, 13, 2934, 2892, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1769, 203, 3639, 2254, 5034, 1131, 5147, 273, 389, 1734, 5147, 18, 16411, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 18, 1717, 12, 1896, 758, 13243, 11494, 291, 5636, 13, 2934, 2892, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1769, 203, 203, 3639, 309, 261, 19731, 280, 12305, 5147, 10756, 288, 203, 5411, 309, 261, 8076, 5147, 1545, 1131, 5147, 597, 4797, 5147, 1648, 943, 5147, 13, 288, 203, 7734, 309, 261, 67, 1896, 381, 784, 13, 288, 203, 10792, 309, 261, 67, 1734, 5147, 405, 4797, 5147, 13, 288, 203, 13491, 2254, 5034, 6626, 5147, 273, 4797, 5147, 18, 16411, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 18, 1289, 12, 15416, 11494, 291, 5636, 13, 2934, 2892, 12, 12536, 15664, 67, 8941, 55, 67, 2565, 26780, 916, 1769, 203, 13491, 327, 6626, 5147, 405, 389, 1734, 5147, 692, 389, 1734, 5147, 294, 6626, 5147, 31, 203, 10792, 289, 203, 10792, 327, 4797, 5147, 31, 203, 7734, 289, 2 ]
pragma solidity 0.6.12; 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.3._ */ 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.3._ */ 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); } } } } 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; } } 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"); } } } 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); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ 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. */ 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. */ 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. */ 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. */ 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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal 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 { } } 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; } } // MoniBooksToken with Governance. contract MoniBooksToken is ERC20("MoniBooks Token", "MNBKS"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // 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 /// @notice 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( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MNBKS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MNBKS::delegateBySig: invalid nonce"); require(now <= expiry, "MNBKS::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, "MNBKS::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 MNBKS (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, "MNBKS::_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; } } interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of MoniBooks. He can make MoniBooks and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once MNBKS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of MNBKSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accMnbksPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accMnbksPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. MNBKS to distribute per block. uint256 lastRewardBlock; // Last block number that MNBKS distribution occurs. uint256 accMnbksPerShare; // Accumulated MNBKS per share, times 1e12. See below. } // The MNBKS TOKEN! MoniBooksToken public mnbks; // Dev address. address public devaddr; // Block number when bonus MNBKS period ends. uint256 public bonusEndBlock; // MNBKS tokens created per block. uint256 public mnbksPerBlock; // Bonus muliplier for early MNBKS makers. uint256 public constant BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when MNBKS mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MoniBooksToken _mnbks, address _devaddr ) public { mnbks = _mnbks; devaddr = _devaddr; mnbksPerBlock = 469000000000000000; bonusEndBlock = block.number; startBlock = block.number; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMnbksPerShare: 0 })); } // Update the given pool's MNBKS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending MNBKS on frontend. function pendingMnbks(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMnbksPerShare = pool.accMnbksPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accMnbksPerShare = accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accMnbksPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mnbks.mint(devaddr, mnbksReward.div(10)); mnbks.mint(address(this), mnbksReward); pool.accMnbksPerShare = pool.accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for MNBKS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe MNBKS transfer function, just in case if rounding error causes pool to not have enough MNBKS. function safeMnbksTransfer(address _to, uint256 _amount) internal { uint256 mnbksBal = mnbks.balanceOf(address(this)); if (_amount > mnbksBal) { mnbks.transfer(_to, mnbksBal); } else { mnbks.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
MasterChef is the master of MoniBooks. He can make MoniBooks and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once MNBKS is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { } struct PoolInfo { } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MoniBooksToken _mnbks, address _devaddr MoniBooksToken public mnbks; address public devaddr; uint256 public bonusEndBlock; uint256 public mnbksPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; IMigratorChef public migrator; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { mnbks = _mnbks; devaddr = _devaddr; mnbksPerBlock = 469000000000000000; bonusEndBlock = block.number; startBlock = block.number; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMnbksPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMnbksPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMnbksPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } } else if (_from >= bonusEndBlock) { } else { function pendingMnbks(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMnbksPerShare = pool.accMnbksPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accMnbksPerShare = accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accMnbksPerShare).div(1e12).sub(user.rewardDebt); } function pendingMnbks(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMnbksPerShare = pool.accMnbksPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accMnbksPerShare = accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accMnbksPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mnbks.mint(devaddr, mnbksReward.div(10)); mnbks.mint(address(this), mnbksReward); pool.accMnbksPerShare = pool.accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mnbks.mint(devaddr, mnbksReward.div(10)); mnbks.mint(address(this), mnbksReward); pool.accMnbksPerShare = pool.accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 mnbksReward = multiplier.mul(mnbksPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mnbks.mint(devaddr, mnbksReward.div(10)); mnbks.mint(address(this), mnbksReward); pool.accMnbksPerShare = pool.accMnbksPerShare.add(mnbksReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accMnbksPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeMnbksTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accMnbksPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function safeMnbksTransfer(address _to, uint256 _amount) internal { uint256 mnbksBal = mnbks.balanceOf(address(this)); if (_amount > mnbksBal) { mnbks.transfer(_to, mnbksBal); mnbks.transfer(_to, _amount); } } function safeMnbksTransfer(address _to, uint256 _amount) internal { uint256 mnbksBal = mnbks.balanceOf(address(this)); if (_amount > mnbksBal) { mnbks.transfer(_to, mnbksBal); mnbks.transfer(_to, _amount); } } } else { function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
1,640,519
[ 1, 7786, 39, 580, 74, 353, 326, 4171, 434, 9041, 77, 9084, 87, 18, 8264, 848, 1221, 9041, 77, 9084, 87, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 490, 20626, 47, 55, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 3807, 434, 1517, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 39, 580, 74, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 3885, 12, 203, 3639, 9041, 77, 9084, 87, 1345, 389, 81, 6423, 7904, 16, 203, 3639, 1758, 389, 5206, 4793, 203, 565, 9041, 77, 9084, 87, 1345, 1071, 312, 6423, 7904, 31, 203, 565, 1758, 1071, 4461, 4793, 31, 203, 565, 2254, 5034, 1071, 324, 22889, 1638, 1768, 31, 203, 565, 2254, 5034, 1071, 312, 6423, 7904, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 404, 31, 203, 565, 6246, 2757, 639, 39, 580, 74, 1071, 30188, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 25003, 3719, 1071, 16753, 31, 203, 565, 2254, 5034, 1071, 2078, 8763, 2148, 273, 374, 31, 203, 565, 2254, 5034, 1071, 787, 1768, 31, 203, 565, 262, 1071, 288, 2 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; 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); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public 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; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } 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; } } contract SkyvToken is StandardToken { string public name = "Skyv Token"; string public symbol = "SKV"; uint public decimals = 18; uint public INIT_SUPPLY = 2100000000 * (10 ** decimals); constructor() public { totalSupply = INIT_SUPPLY; balances[msg.sender] = INIT_SUPPLY; emit Transfer(0x0, msg.sender, INIT_SUPPLY); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } }
SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
1,818,159
[ 1, 9890, 10477, 18, 1717, 903, 604, 309, 1915, 353, 486, 7304, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xeACa7559F81dADE5d11fE8852E832a699396aBB7/sources/contracts/strategies/OptimizerAPR/genericLender/euler/GenericEuler.sol
@inheritdoc IGenericLender
function emergencyWithdraw(uint256 amount) external override onlyRole(GUARDIAN_ROLE) { _unstake(amount); eToken.withdraw(0, amount); want.safeTransfer(address(poolManager), want.balanceOf(address(this))); }
4,957,334
[ 1, 36, 10093, 467, 7014, 48, 2345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 801, 24530, 1190, 9446, 12, 11890, 5034, 3844, 13, 3903, 3849, 1338, 2996, 12, 30673, 985, 2565, 1258, 67, 16256, 13, 288, 203, 3639, 389, 23412, 911, 12, 8949, 1769, 203, 3639, 425, 1345, 18, 1918, 9446, 12, 20, 16, 3844, 1769, 203, 3639, 2545, 18, 4626, 5912, 12, 2867, 12, 6011, 1318, 3631, 2545, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBf7EE8D41fA851fa94D4E908209aD1A97E13EDD9/sources/POE/PoExtended.sol
@dev only owner can add minters
function addMinter(address _minter) external onlyOwner{ require(approved_minters[_minter] != true, "Minter is already approved"); approved_minters[_minter] = true; }
3,179,266
[ 1, 3700, 3410, 848, 527, 1131, 5432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 49, 2761, 12, 2867, 389, 1154, 387, 13, 3903, 1338, 5541, 95, 203, 3639, 2583, 12, 25990, 67, 1154, 5432, 63, 67, 1154, 387, 65, 480, 638, 16, 315, 49, 2761, 353, 1818, 20412, 8863, 203, 3639, 20412, 67, 1154, 5432, 63, 67, 1154, 387, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9a5132e149c547F254C73226DA7f770d43D9EA44/sources/contracts/periphery/libraries/Path.sol
@notice Decodes the first pool in path @param path The bytes encoded swap path @return tokenA The first token of the given pool @return tokenB The second token of the given pool
function decodeFirstPool(bytes memory path) internal pure returns (address tokenA, address tokenB) { tokenA = path.toAddress(0); tokenB = path.toAddress(NEXT_OFFSET); }
2,733,420
[ 1, 20978, 326, 1122, 2845, 316, 589, 225, 589, 1021, 1731, 3749, 7720, 589, 327, 1147, 37, 1021, 1122, 1147, 434, 326, 864, 2845, 327, 1147, 38, 1021, 2205, 1147, 434, 326, 864, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2495, 3759, 2864, 12, 3890, 3778, 589, 13, 2713, 16618, 1135, 261, 2867, 1147, 37, 16, 1758, 1147, 38, 13, 288, 203, 3639, 1147, 37, 273, 589, 18, 869, 1887, 12, 20, 1769, 203, 3639, 1147, 38, 273, 589, 18, 869, 1887, 12, 25539, 67, 11271, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // 'ACT275170' token contract // // Deployed to : 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187 // Symbol : ACT275170 // Name : ADZbuzz Forentrepreneurs.com Community Token // Total supply: 2000000 // Decimals : 8 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // (c) by Darwin Jayme with ADZbuzz Ltd. UK (adzbuzz.com) 2018. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ADZbuzzCommunityToken() public { symbol = "ACT275170"; name = "ADZbuzz Forentrepreneurs.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ADZbuzzCommunityToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function ADZbuzzCommunityToken() public { symbol = "ACT275170"; name = "ADZbuzz Forentrepreneurs.com Community Token"; decimals = 8; _totalSupply = 200000000000000; balances[0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187] = _totalSupply; emit Transfer(address(0), 0x3f70c0B02879c36162C2C902ECfe9Ac0a8a8a187, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,262,179
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6835, 11738, 62, 70, 9510, 12136, 13352, 1345, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 3639, 533, 1071, 3273, 31, 203, 3639, 533, 1071, 225, 508, 31, 203, 3639, 2254, 28, 1071, 15105, 31, 203, 3639, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 377, 203, 3639, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 377, 203, 377, 203, 3639, 445, 11738, 62, 70, 9510, 12136, 13352, 1345, 1435, 1071, 288, 203, 5411, 3273, 273, 315, 6526, 5324, 25, 31779, 14432, 203, 5411, 508, 273, 315, 1880, 62, 70, 9510, 17605, 496, 14462, 1187, 73, 25152, 18, 832, 16854, 13352, 3155, 14432, 203, 5411, 15105, 273, 1725, 31, 203, 5411, 389, 4963, 3088, 1283, 273, 576, 12648, 9449, 31, 203, 5411, 324, 26488, 63, 20, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 65, 273, 389, 4963, 3088, 1283, 31, 203, 5411, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 23, 74, 7301, 71, 20, 38, 3103, 28, 7235, 71, 5718, 30042, 39, 22, 39, 29, 3103, 7228, 3030, 29, 9988, 20, 69, 28, 69, 28, 69, 2643, 27, 16, 389, 4963, 3088, 1283, 1769, 203, 3639, 289, 203, 377, 203, 377, 203, 3639, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 5411, 2 ]
./partial_match/1/0x000000000000f968845afB0B8Cf134Ec196D38D4/sources/contracts/controller/ArrngController.sol
* @dev withdrawERC721: Pull ERC721s (likely only the ENS associated with this contract) to the treasuryAddress. @param erc721Address_: The token contract for the withdrawal @param tokenIDs_: the list of tokenIDs for the withdrawal/
function withdrawERC721( address erc721Address_, uint256[] memory tokenIDs_ ) external onlyOwner { require( treasuryAddress != address(0), "Cannot withdraw to a treasury at address(0)" ); for (uint256 i = 0; i < tokenIDs_.length; ) { IERC721(erc721Address_).transferFrom( address(this), treasuryAddress, tokenIDs_[i] ); unchecked { ++i; } } }
15,927,256
[ 1, 1918, 9446, 654, 39, 27, 5340, 30, 14899, 4232, 39, 27, 5340, 87, 261, 24178, 1338, 326, 512, 3156, 3627, 598, 333, 6835, 13, 358, 326, 9787, 345, 22498, 1887, 18, 225, 6445, 71, 27, 5340, 1887, 67, 30, 1021, 1147, 6835, 364, 326, 598, 9446, 287, 225, 1147, 5103, 67, 30, 326, 666, 434, 1147, 5103, 364, 326, 598, 9446, 287, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 598, 9446, 654, 39, 27, 5340, 12, 203, 565, 1758, 6445, 71, 27, 5340, 1887, 67, 16, 203, 565, 2254, 5034, 8526, 3778, 1147, 5103, 67, 203, 225, 262, 3903, 1338, 5541, 288, 203, 565, 2583, 12, 203, 1377, 9787, 345, 22498, 1887, 480, 1758, 12, 20, 3631, 203, 1377, 315, 4515, 598, 9446, 358, 279, 9787, 345, 22498, 622, 1758, 12, 20, 2225, 203, 565, 11272, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 5103, 27799, 2469, 31, 262, 288, 203, 1377, 467, 654, 39, 27, 5340, 12, 12610, 27, 5340, 1887, 67, 2934, 13866, 1265, 12, 203, 3639, 1758, 12, 2211, 3631, 203, 3639, 9787, 345, 22498, 1887, 16, 203, 3639, 1147, 5103, 67, 63, 77, 65, 203, 1377, 11272, 203, 1377, 22893, 288, 203, 3639, 965, 77, 31, 203, 1377, 289, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; /** * @notice This ERC20 is only for the testnet. */ contract RewardAsset is ERC20 { constructor() ERC20('Reward', 'Reward') { _mint(msg.sender, 1e30 / 2); _mint(address(this), 1e30 / 2); } /** * @notice The faucet is for testing ELYFI functions */ function faucet() external { _transfer(address(this), msg.sender, 10000 * 1e18); } }
* @notice This ERC20 is only for the testnet./
contract RewardAsset is ERC20 { pragma solidity 0.8.4; constructor() ERC20('Reward', 'Reward') { _mint(msg.sender, 1e30 / 2); _mint(address(this), 1e30 / 2); } function faucet() external { _transfer(address(this), msg.sender, 10000 * 1e18); } }
112,271
[ 1, 2503, 4232, 39, 3462, 353, 1338, 364, 326, 1842, 2758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 534, 359, 1060, 6672, 353, 4232, 39, 3462, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 225, 3885, 1435, 4232, 39, 3462, 2668, 17631, 1060, 2187, 296, 17631, 1060, 6134, 288, 203, 565, 389, 81, 474, 12, 3576, 18, 15330, 16, 404, 73, 5082, 342, 576, 1769, 203, 565, 389, 81, 474, 12, 2867, 12, 2211, 3631, 404, 73, 5082, 342, 576, 1769, 203, 225, 289, 203, 203, 225, 445, 11087, 5286, 278, 1435, 3903, 288, 203, 565, 389, 13866, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 12619, 380, 404, 73, 2643, 1769, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7d000609a3c0C6Ba13DD318E56934CB5523Ba431/sources/SolomonSale.sol
@notice Set the maximum amount of ETH (wei) each address can exchange
function setMaximumExchange(uint256 newMaximum) external onlyOwner { _maximum = newMaximum; }
4,344,245
[ 1, 694, 326, 4207, 3844, 434, 512, 2455, 261, 1814, 77, 13, 1517, 1758, 848, 7829, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10851, 2422, 11688, 12, 11890, 5034, 394, 13528, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 15724, 273, 394, 13528, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.17; /** * @title Multisignature wallet - Allows multiple parties to agree on * transactions before execution. * * @author Stefan George - <[email protected]> * */ contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); /* * Constants */ uint256 public constant MAX_OWNER_COUNT = 50; /* * Storage */ mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint256 transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint256 transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint256 transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint256 transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @notice Fallback function allows to deposit ether. function() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /** * @notice Contract constructor sets initial owners and required number * of confirmations. * * @param _owners List of initial owners. * @param _required Number of required confirmations. * */ constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required) { for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /** * @notice Allows to add a new owner. Transaction has to be sent by wallet. * @param owner Address of new owner. * */ function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /** * @notice Allows to remove an owner. Transaction has to be sent by wallet. * @param owner Address of owner. * */ function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /** * @notice Allows to replace an owner with a new owner. Transaction has * to be sent by wallet. * * @param owner Address of owner to be replaced. * @param newOwner Address of new owner. * */ function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /** * @notice Allows to change the number of required confirmations. * Transaction has to be sent by wallet. * * @param _required Number of required confirmations. * */ function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /** * @notice Allows an owner to submit and confirm a transaction. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * * @return Returns transaction ID. * */ function submitTransaction( address destination, uint256 value, bytes memory data ) public returns (uint256 transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /** * @notice Allows an owner to confirm a transaction. * @param transactionId Transaction ID. * */ function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /** * @notice Allows an owner to revoke a confirmation for a transaction. * @param transactionId Transaction ID. * */ function revokeConfirmation(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /** * @notice Allows anyone to execute a confirmed transaction. * @param transactionId Transaction ID. * */ function executeTransaction(uint256 transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); txn.executed = false; } } } /** * @notice Low level transaction execution. * * @dev Call has been separated into its own function in order to * take advantage of the Solidity's code generator to produce a * loop that copies tx.data into memory. * * @param destination The address of the Smart Contract to call. * @param value The amout of rBTC to send w/ the transaction. * @param dataLength The size of the payload. * @param data The payload. * * @return Success or failure. * */ function external_call( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; assembly { let x := mload(0x40) /// "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) /// First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), /// 34710 is the value that solidity is currently emitting /// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + /// callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, /// Size of the input (in bytes) - this is what fixes the padding problem x, 0 /// Output is ignored, therefore the output size is zero ) } return result; } /** * @notice Returns the confirmation status of a transaction. * @param transactionId Transaction ID. * @return Confirmation status. * */ function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } return false; } /* * Internal functions */ /** * @notice Adds a new transaction to the transaction mapping, * if transaction does not exist yet. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * * @return Returns transaction ID. * */ function addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); } /* * Web3 call functions */ /** * @notice Get the number of confirmations of a transaction. * @param transactionId Transaction ID. * @return Number of confirmations. * */ function getConfirmationCount(uint256 transactionId) public view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /** * @notice Get the total number of transactions after filers are applied. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. * */ function getTransactionCount(bool pending, bool executed) public view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) count += 1; } /** * @notice Get the list of owners. * @return List of owner addresses. * */ function getOwners() public view returns (address[] memory) { return owners; } /** * @notice Get the array with owner addresses, which confirmed transaction. * @param transactionId Transaction ID. * @return Returns array of owner addresses. * */ function getConfirmations(uint256 transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /** * @notice Get the list of transaction IDs in defined range. * * @param from Index start position of transaction array. * @param to Index end position of transaction array. * @param pending Include pending transactions. * @param executed Include executed transactions. * * @return Returns array of transaction IDs. * */ function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory _transactionIds) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) if ((pending && !transactions[i].executed) || (executed && transactions[i].executed)) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } }
* @notice Low level transaction execution. @dev Call has been separated into its own function in order to take advantage of the Solidity's code generator to produce a loop that copies tx.data into memory. @param destination The address of the Smart Contract to call. @param value The amout of rBTC to send w/ the transaction. @param dataLength The size of the payload. @param data The payload. @return Success or failure. /
function external_call( address destination, uint256 value, uint256 dataLength, bytes memory data ) internal returns (bool) { bool result; assembly { result := call( destination, value, d, x, ) return result; }
14,958,198
[ 1, 10520, 1801, 2492, 4588, 18, 225, 3049, 711, 2118, 8936, 1368, 2097, 4953, 445, 316, 1353, 358, 282, 4862, 1261, 7445, 410, 434, 326, 348, 7953, 560, 1807, 981, 4456, 358, 11402, 279, 282, 2798, 716, 13200, 2229, 18, 892, 1368, 3778, 18, 225, 2929, 1021, 1758, 434, 326, 19656, 13456, 358, 745, 18, 225, 460, 1021, 2125, 659, 434, 436, 38, 15988, 358, 1366, 341, 19, 326, 2492, 18, 225, 27972, 1021, 963, 434, 326, 2385, 18, 225, 501, 1021, 2385, 18, 327, 11958, 578, 5166, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 3903, 67, 1991, 12, 203, 202, 202, 2867, 2929, 16, 203, 202, 202, 11890, 5034, 460, 16, 203, 202, 202, 11890, 5034, 27972, 16, 203, 202, 202, 3890, 3778, 501, 203, 202, 13, 2713, 1135, 261, 6430, 13, 288, 203, 202, 202, 6430, 563, 31, 203, 202, 202, 28050, 288, 203, 1082, 202, 2088, 519, 745, 12, 203, 9506, 202, 10590, 16, 203, 9506, 202, 1132, 16, 203, 9506, 202, 72, 16, 203, 9506, 202, 92, 16, 203, 1082, 202, 13, 203, 202, 202, 2463, 563, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x51290AB14d595E1D7ad008e8a538A83d252E3B40/sources/project:/contracts/superfluid/PoolMemberNFT.sol
update mapping for new NFT to be minted
_poolMemberDataByTokenId[newTokenId] = PoolMemberNFTData(pool, member, units);
859,593
[ 1, 2725, 2874, 364, 394, 423, 4464, 358, 506, 312, 474, 329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 6011, 4419, 751, 858, 1345, 548, 63, 2704, 1345, 548, 65, 273, 8828, 4419, 50, 4464, 751, 12, 6011, 16, 3140, 16, 4971, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9a5132e149c547F254C73226DA7f770d43D9EA44/sources/contracts/periphery/libraries/PoolHelpers.sol
* @notice fetches the priceAverage for a pair @param _factory the factory address @param _tokenA token to fetch priceAverage @param _tokenB token to fetch priceAverage @return priceAverageA_ priceAverage of tokenA in the pair tokenA/TokenB @return priceAverageB_ priceAverage of tokenB in the pair tokenA/TokenB/
function getPriceAverage( address _factory, address _tokenA, address _tokenB ) internal view returns (uint256 priceAverageA_, uint256 priceAverageB_) { (address _token0, ) = sortTokens(_tokenA, _tokenB); (uint256 _priceAverage0, uint256 _priceAverage1, ) = ISmardexPair( PoolAddress.pairFor(_factory, _tokenA, _tokenB) ).getPriceAverage(); (priceAverageA_, priceAverageB_) = _tokenA == _token0 ? (_priceAverage0, _priceAverage1) : (_priceAverage1, _priceAverage0); }
2,733,412
[ 1, 5754, 281, 326, 6205, 17115, 364, 279, 3082, 225, 389, 6848, 326, 3272, 1758, 225, 389, 2316, 37, 1147, 358, 2158, 6205, 17115, 225, 389, 2316, 38, 1147, 358, 2158, 6205, 17115, 327, 6205, 17115, 37, 67, 6205, 17115, 434, 1147, 37, 316, 326, 3082, 1147, 37, 19, 1345, 38, 327, 6205, 17115, 38, 67, 6205, 17115, 434, 1147, 38, 316, 326, 3082, 1147, 37, 19, 1345, 38, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25930, 17115, 12, 203, 3639, 1758, 389, 6848, 16, 203, 3639, 1758, 389, 2316, 37, 16, 203, 3639, 1758, 389, 2316, 38, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 6205, 17115, 37, 67, 16, 2254, 5034, 6205, 17115, 38, 67, 13, 288, 203, 3639, 261, 2867, 389, 2316, 20, 16, 262, 273, 1524, 5157, 24899, 2316, 37, 16, 389, 2316, 38, 1769, 203, 3639, 261, 11890, 5034, 389, 8694, 17115, 20, 16, 2254, 5034, 389, 8694, 17115, 21, 16, 262, 273, 4437, 3684, 561, 4154, 12, 203, 5411, 8828, 1887, 18, 6017, 1290, 24899, 6848, 16, 389, 2316, 37, 16, 389, 2316, 38, 13, 203, 3639, 262, 18, 588, 5147, 17115, 5621, 203, 3639, 261, 8694, 17115, 37, 67, 16, 6205, 17115, 38, 67, 13, 273, 389, 2316, 37, 422, 389, 2316, 20, 203, 5411, 692, 261, 67, 8694, 17115, 20, 16, 389, 8694, 17115, 21, 13, 203, 5411, 294, 261, 67, 8694, 17115, 21, 16, 389, 8694, 17115, 20, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-09-29 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/Ownable.sol pragma solidity 0.6.10; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the a * specified account. * @param initalOwner The address of the inital owner. */ constructor(address initalOwner) internal { _owner = initalOwner; 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(), "Only owner can call"); _; } /** * @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. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev 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), "Owner should not be 0 address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/TokenPool.sol pragma solidity 0.6.10; /** * @title A simple holder of tokens. * This is a simple contract to hold tokens. It's useful in the case where a separate contract * needs to hold multiple distinct pools of the same token. */ contract TokenPool is Ownable { IERC20 public token; constructor(IERC20 _token) Ownable(msg.sender) public { token = _token; } function balance() public view returns (uint256) { return token.balanceOf(address(this)); } function transfer(address to, uint256 value) external onlyOwner returns (bool) { return token.transfer(to, value); } } // File: contracts/AbstractStaking.sol pragma solidity 0.6.10; /** * @title Abstract Staking * @dev Skeleton of the staking pool for user to stake Balancer BPT token and get bella as reward. */ abstract contract AbstractStaking is Ownable { using SafeMath for uint256; event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 amount); event Claimed(address indexed user, uint256 amount); TokenPool public stakingPool; TokenPool public lockedPool; TokenPool public unlockedPool; uint256 public startTime; // // Global state // uint256 public totalStakingAmount; uint256 public totalStakingAmountTime; // total time * amount staked uint256 public lastUpdatedTimestamp; // // Addional bella locking related // uint256 public currentUnlockCycle; // linear count down to release bella token uint256 public lastUnlockTime; /** * @param stakingBPT The BPT token users deposit as stake. * @param bellaToken The bonus token is bella. * @param admin The admin address * @param _startTime Timestamp that user can stake */ constructor( IERC20 stakingBPT, IERC20 bellaToken, address admin, uint256 _startTime ) Ownable(admin) internal { stakingPool = new TokenPool(stakingBPT); lockedPool = new TokenPool(bellaToken); unlockedPool = new TokenPool(bellaToken); startTime = _startTime; } /** * @return The user's total staking BPT amount */ function totalStakedFor(address user) public view virtual returns (uint256); function totalStaked() public view returns (uint256) { return totalStakingAmount; } /** * @dev Stake for the user self * @param amount The amount of BPT tokens that the user wishes to stake */ function stake(uint256 amount) external { require(!Address.isContract(msg.sender), "No harvest thanks"); require(now >= startTime, "not started yet"); _stake(msg.sender, msg.sender, amount); } /** * @return User's total rewards when clamining */ function totalRewards() external view returns (uint256) { return _totalRewardsFor(msg.sender); } /** * @return A specific user's total rewards when clamining */ function totalRewardsFor(address user) external view returns (uint256) { return _totalRewardsFor(user); } /** * @dev Claim=withdraw all the bella rewards */ function claim() external { require(!Address.isContract(msg.sender), "No harvest thanks"); // cumulate user and global time*amount _updateTotalStaking(0); _updateUserStaking(0, msg.sender); _poolUnlock(); uint256 reward = _calculateRewardAndBurnAll(msg.sender); unlockedPool.transfer(msg.sender, reward); emit Claimed(msg.sender, reward); } /** * @dev Claim=withdraw all the bella rewards and the staking BPT token, * which stops the user's staking */ function claimAndUnstake() external { require(!Address.isContract(msg.sender), "No harvest thanks"); // cumulate user and global time*amount _updateTotalStaking(0); _updateUserStaking(0, msg.sender); _poolUnlock(); (uint256 staking, uint256 reward) = _calculateRewardAndCleanUser(msg.sender); unlockedPool.transfer(msg.sender, reward); stakingPool.transfer(msg.sender, staking); emit Claimed(msg.sender, reward); emit Unstaked(msg.sender, staking); } /** * @dev we will lock more bella tokens on the begining of the next releasing cycle * @param amount the amount of bella token to lock * @param nextUnlockCycle next reward releasing cycle, unit=day */ function lock(uint256 amount, uint256 nextUnlockCycle) external onlyOwner { currentUnlockCycle = nextUnlockCycle * 1 days; if (now >= startTime) { lastUnlockTime = now; } else { lastUnlockTime = startTime; } require( lockedPool.token().transferFrom(msg.sender, address(lockedPool), amount), "Additional bella transfer failed" ); } /** * @dev Actual logic to handle user staking * @param from The user who pays the staking BPT * @param beneficiary The user who actually controls the staking BPT * @param amount The amount of BPT tokens to stake */ function _stake(address from, address beneficiary, uint256 amount) private { require(amount > 0, "can not stake 0 token"); require( stakingPool.token().transferFrom(from, address(stakingPool), amount), "Staking BPT transfer failed" ); _updateUserStaking(amount, beneficiary); _updateTotalStaking(amount); emit Staked(beneficiary, amount); } /** * @dev Update the global state due to more time cumulated and/or new BPT staking token * @param amount New BPT staking deposited (can be 0) */ function _updateTotalStaking(uint256 amount) private { uint256 additionalAmountTime = totalStakingAmount.mul(now.sub(lastUpdatedTimestamp)); totalStakingAmount = totalStakingAmount.add(amount); totalStakingAmountTime = totalStakingAmountTime.add(additionalAmountTime); lastUpdatedTimestamp = now; } /** * @dev Update a specific user's state due to more time cumulated and/or new BPT staking token * @param amount New BPT staking deposited (can be 0) * @param user The account to be updated */ function _updateUserStaking(uint256 amount, address user) internal virtual; /** * @dev linear count down from 30 days to release bella token, * from the locked pool to the unlocked pool */ function _poolUnlock() private { if (currentUnlockCycle == 0) return; // release ended uint256 timeDelta = now.sub(lastUnlockTime); if (currentUnlockCycle < timeDelta) currentUnlockCycle = timeDelta; // release all uint256 amount = lockedPool.balance().mul(timeDelta).div(currentUnlockCycle); currentUnlockCycle = currentUnlockCycle.sub(timeDelta); lastUnlockTime = now; lockedPool.transfer(address(unlockedPool), amount); } /** * @dev Calculate user's total cumulated reward and burn his/her all staking amount*time * @return User cumulated reward bella during the staking process */ function _calculateRewardAndBurnAll(address user) internal virtual returns (uint256); /** * @dev Calculate user's total cumulated reward and staking, * and remove him/her from the staking process * @return [1] User cumulated staking BPT * @return [2] User cumulated reward bella during the staking process */ function _calculateRewardAndCleanUser(address user) internal virtual returns (uint256, uint256); /** * @dev Internal function to calculate user's total rewards * @return A specific user's total rewards when clamining */ function _totalRewardsFor(address user) internal view virtual returns (uint256); } // File: contracts/LinearStaking.sol pragma solidity 0.6.10; /** * @title Linear Staking * @dev A staking pool for user to stake Balancer BPT token and get bella as reward. * The reward is always proportional to the amount*time of the staking. * The reward is added by the admin at the 0th, 30th and 60th day, respectively. */ contract LinearStaking is AbstractStaking { using SafeMath for uint256; mapping(address=>Staking) public stakingInfo; struct Staking { uint256 amount; uint256 totalAmountTime; // staking amount*time uint256 lastUpdatedTimestamp; } /** * @param stakingBPT The BPT token users deposit as stake. * @param bellaToken The bonus token is bella. * @param admin The admin address * @param _startTime Timestamp that user can stake */ constructor( IERC20 stakingBPT, IERC20 bellaToken, address admin, uint256 _startTime ) AbstractStaking( stakingBPT, bellaToken, admin, _startTime ) public {} /** * @return The user's total staking BPT amount */ function totalStakedFor(address user) public view override returns (uint256) { return stakingInfo[user].amount; } /** * @dev Update a specific user's state due to more time cumulated and/or new BPT staking token * @param amount New BPT staking deposited (can be 0) * @param user The account to be updated */ function _updateUserStaking(uint256 amount, address user) internal override { Staking memory userInfo = stakingInfo[user]; uint256 additionalAmountTime = userInfo.amount.mul(now.sub(userInfo.lastUpdatedTimestamp)); userInfo.totalAmountTime = userInfo.totalAmountTime.add(additionalAmountTime); userInfo.amount = userInfo.amount.add(amount); userInfo.lastUpdatedTimestamp = now; stakingInfo[user] = userInfo; } /** * @dev Calculate user's total cumulated reward and burn his/her all staking amount*time * @return User cumulated reward bella during the staking process */ function _calculateRewardAndBurnAll(address user) internal override returns (uint256) { Staking memory userInfo = stakingInfo[user]; uint256 reward = unlockedPool.balance().mul(userInfo.totalAmountTime).div(totalStakingAmountTime); totalStakingAmountTime = totalStakingAmountTime.sub(userInfo.totalAmountTime); stakingInfo[user].totalAmountTime = 0; return reward; } /** * @dev Calculate user's total cumulated reward and staking, * and remove him/her from the staking process * @return [1] User cumulated staking BPT * @return [2] User cumulated reward bella during the staking process */ function _calculateRewardAndCleanUser(address user) internal override returns (uint256, uint256) { Staking memory userInfo = stakingInfo[user]; uint256 reward = unlockedPool.balance().mul(userInfo.totalAmountTime).div(totalStakingAmountTime); uint256 staking = userInfo.amount; totalStakingAmountTime = totalStakingAmountTime.sub(userInfo.totalAmountTime); totalStakingAmount = totalStakingAmount.sub(userInfo.amount); delete stakingInfo[user]; return (staking, reward); } /** * @dev Internal function to calculate user's total rewards * @return A specific user's total rewards when clamining */ function _totalRewardsFor(address user) internal view override returns (uint256) { // calculate new total staking amount*time uint256 additionalAmountTime = totalStakingAmount.mul(now.sub(lastUpdatedTimestamp)); uint256 newTotalStakingAmountTime = totalStakingAmountTime.add(additionalAmountTime); // calculate new user staking Staking memory userInfo = stakingInfo[user]; uint256 additionalUserAmountTime = userInfo.amount.mul(now.sub(userInfo.lastUpdatedTimestamp)); uint256 newUserTotalAmountTime = userInfo.totalAmountTime.add(additionalUserAmountTime); // calculate total unlocked pool uint256 unlockedAmount = unlockedPool.balance(); if (currentUnlockCycle != 0) { uint256 timeDelta = now.sub(lastUnlockTime); if (currentUnlockCycle < timeDelta) { unlockedAmount = unlockedAmount.add(lockedPool.balance()); } else { uint256 additionalAmount = lockedPool.balance().mul(timeDelta).div(currentUnlockCycle); unlockedAmount = unlockedAmount.add(additionalAmount); } } uint256 reward = unlockedAmount.mul(newUserTotalAmountTime).div(newTotalStakingAmountTime); return reward; } }
* @return The user's total staking BPT amount/
function totalStakedFor(address user) public view override returns (uint256) { return stakingInfo[user].amount; }
6,259,507
[ 1, 2463, 1021, 729, 1807, 2078, 384, 6159, 605, 1856, 3844, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 510, 9477, 1290, 12, 2867, 729, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 384, 6159, 966, 63, 1355, 8009, 8949, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* file: Base.sol ver: 0.2.1 updated:18-Nov-2016 author: Darryl Morris (o0ragman0o) email: o0ragman0o AT gmail.com An basic contract furnishing inheriting contracts with ownership, reentry protection and safe sending functions. This software 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 lesser General Public License for more details. <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.0; contract Base { /* Constants */ string constant VERSION = "Base 0.1.1 \n"; /* State Variables */ bool mutex; address public owner; /* Events */ event Log(string message); event ChangedOwner(address indexed oldOwner, address indexed newOwner); /* Modifiers */ // To throw call not made by owner modifier onlyOwner() { if (msg.sender != owner) throw; _; } // This modifier can be used on functions with external calls to // prevent reentry attacks. // Constraints: // Protected functions must have only one point of exit. // Protected functions cannot use the `return` keyword // Protected functions return values must be through return parameters. modifier preventReentry() { if (mutex) throw; else mutex = true; _; delete mutex; return; } // This modifier can be applied to pulic access state mutation functions // to protect against reentry if a `mutextProtect` function is already // on the call stack. modifier noReentry() { if (mutex) throw; _; } // Same as noReentry() but intended to be overloaded modifier canEnter() { if (mutex) throw; _; } /* Functions */ function Base() { owner = msg.sender; } function version() public constant returns (string) { return VERSION; } function contractBalance() public constant returns(uint) { return this.balance; } // Change the owner of a contract function changeOwner(address _newOwner) public onlyOwner returns (bool) { owner = _newOwner; ChangedOwner(msg.sender, owner); return true; } function safeSend(address _recipient, uint _ether) internal preventReentry() returns (bool success_) { if(!_recipient.call.value(_ether)()) throw; success_ = true; } } /* End of Base */ /* file: Math.sol ver: 0.2.0 updated:18-Nov-2016 author: Darryl Morris email: o0ragman0o AT gmail.com An inheritable contract containing math functions and comparitors. This software 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 lesser General Public License for more details. <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.0; contract Math { /* Constants */ string constant VERSION = "Math 0.0.1 \n"; uint constant NULL = 0; bool constant LT = false; bool constant GT = true; // No type bool <-> int type converstion in solidity :~( uint constant iTRUE = 1; uint constant iFALSE = 0; uint constant iPOS = 1; uint constant iZERO = 0; uint constant iNEG = uint(-1); /* Modifiers */ /* Functions */ function version() public constant returns (string) { return VERSION; } function assert(bool assertion) internal constant { if (!assertion) throw; } // @dev Parametric comparitor for > or < // !_sym returns a < b // _sym returns a > b function cmp (uint a, uint b, bool _sym) internal constant returns (bool) { return (a!=b) && ((a < b) != _sym); } /// @dev Parametric comparitor for >= or <= /// !_sym returns a <= b /// _sym returns a >= b function cmpEq (uint a, uint b, bool _sym) internal constant returns (bool) { return (a==b) || ((a < b) != _sym); } /// Trichotomous comparitor /// a < b returns -1 /// a == b returns 0 /// a > b returns 1 /* function triCmp(uint a, uint b) internal constant returns (bool) { uint c = a - b; return c & c & (0 - 1); } function nSign(uint a) internal returns (uint) { return a & 2^255; } function neg(uint a) internal returns (uint) { return 0 - a; } */ function safeMul(uint a, uint b) internal constant returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal constant returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal constant returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } /* End of Math */ /* file: ERC20.sol ver: 0.2.3 updated:18-Nov-2016 author: Darryl Morris email: o0ragman0o AT gmail.com An ERC20 compliant token. This software 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 lesser General Public License for more details. <http://www.gnu.org/licenses/>. */ //pragma solidity ^0.4.0; //import "Math.sol"; //import "Base.sol"; // ERC20 Standard Token Interface with safe maths and reentry protection contract ERC20Interface { /* Structs */ /* Constants */ string constant VERSION = "ERC20 0.2.3-o0ragman0o\nMath 0.0.1\nBase 0.1.1\n"; /* State Valiables */ uint public totalSupply; uint8 public decimalPlaces; string public name; string public symbol; // Token ownership mapping // mapping (address => uint) public balanceOf; mapping (address => uint) balance; // Transfer allowances mapping mapping (address => mapping (address => uint)) public allowance; /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval( address indexed _owner, address indexed _spender, uint256 _value); /* Modifiers */ /* Function Abstracts */ /* State variable Accessor Functions (for reference - leave commented) */ // Returns the allowable transfer of tokens by a proxy // function allowance (address tokenHolders, address proxy, uint allowance) public constant returns (uint); // Get the total token supply // function totalSupply() public constant returns (uint); // Returns token symbol // function symbol() public constant returns(string); // Returns token symbol // function name() public constant returns(string); // Returns decimal places designated for unit of token. // function decimalPlaces() public returns(uint); // Send _value amount of tokens to address _to // function transfer(address _to, uint256 _value) public returns (bool success); // Send _value amount of tokens from address _from to address _to // function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. // function approve(address _spender, uint256 _value) public returns (bool success); } contract ERC20Token is Base, Math, ERC20Interface { /* Events */ /* Structs */ /* Constants */ /* State Valiables */ /* Modifiers */ modifier isAvailable(uint _amount) { if (_amount > balance[msg.sender]) throw; _; } modifier isAllowed(address _from, uint _amount) { if (_amount > allowance[_from][msg.sender] || _amount > balance[_from]) throw; _; } /* Funtions Public */ function ERC20Token( uint _supply, uint8 _decimalPlaces, string _symbol, string _name) { totalSupply = _supply; decimalPlaces = _decimalPlaces; symbol = _symbol; name = _name; balance[msg.sender] = totalSupply; } function version() public constant returns(string) { return VERSION; } function balanceOf(address _addr) public constant returns (uint) { return balance[_addr]; } // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) external canEnter isAvailable(_value) returns (bool) { balance[msg.sender] = safeSub(balance[msg.sender], _value); balance[_to] = safeAdd(balance[_to], _value); Transfer(msg.sender, _to, _value); return true; } // Send _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) external canEnter isAllowed(_from, _value) returns (bool) { balance[_from] = safeSub(balance[_from], _value); balance[_to] = safeAdd(balance[_to], _value); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); Transfer(msg.sender, _to, _value); return true; } // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the current // allowance with _value. function approve(address _spender, uint256 _value) external canEnter returns (bool success) { if (balance[msg.sender] == 0) throw; allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } /* End of ERC20 */ /* file: LibCLL.sol ver: 0.3.1 updated:21-Sep-2016 author: Darryl Morris email: o0ragman0o AT gmail.com A Solidity library for implementing a data indexing regime using a circular linked list. This library provisions lookup, navigation and key/index storage functionality which can be used in conjunction with an array or mapping. NOTICE: This library uses internal functions only and so cannot be compiled and deployed independently from its calling contract. This library 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 lesser General Public License for more details. <http://www.gnu.org/licenses/>. */ //pragma solidity ^0.4.0; // LibCLL using `uint` keys library LibCLLu { string constant VERSION = "LibCLLu 0.3.1"; uint constant NULL = 0; uint constant HEAD = NULL; bool constant PREV = false; bool constant NEXT = true; struct CLL{ mapping (uint => mapping (bool => uint)) cll; } // n: node id d: direction r: return node id function version() internal constant returns (string) { return VERSION; } // Return existential state of a list. function exists(CLL storage self) internal constant returns (bool) { if (self.cll[HEAD][PREV] != HEAD || self.cll[HEAD][NEXT] != HEAD) return true; } // Returns the number of elements in the list function sizeOf(CLL storage self) internal constant returns (uint r) { uint i = step(self, HEAD, NEXT); while (i != HEAD) { i = step(self, i, NEXT); r++; } return; } // Returns the links of a node as and array function getNode(CLL storage self, uint n) internal constant returns (uint[2]) { return [self.cll[n][PREV], self.cll[n][NEXT]]; } // Returns the link of a node `n` in direction `d`. function step(CLL storage self, uint n, bool d) internal constant returns (uint) { return self.cll[n][d]; } // Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d` function seek(CLL storage self, uint a, uint b, bool d) internal constant returns (uint r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; } // Creates a bidirectional link between two nodes on direction `d` function stitch(CLL storage self, uint a, uint b, bool d) internal { self.cll[b][!d] = a; self.cll[a][d] = b; } // Insert node `b` beside and existing node `a` in direction `d`. function insert (CLL storage self, uint a, uint b, bool d) internal { uint c = self.cll[a][d]; stitch (self, a, b, d); stitch (self, b, c, d); } function remove(CLL storage self, uint n) internal returns (uint) { if (n == NULL) return; stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT); delete self.cll[n][PREV]; delete self.cll[n][NEXT]; return n; } function push(CLL storage self, uint n, bool d) internal { insert(self, HEAD, n, d); } function pop(CLL storage self, bool d) internal returns (uint) { return remove(self, step(self, HEAD, d)); } } // LibCLL using `int` keys library LibCLLi { string constant VERSION = "LibCLLi 0.3.1"; int constant NULL = 0; int constant HEAD = NULL; bool constant PREV = false; bool constant NEXT = true; struct CLL{ mapping (int => mapping (bool => int)) cll; } // n: node id d: direction r: return node id function version() internal constant returns (string) { return VERSION; } // Return existential state of a node. n == HEAD returns list existence. function exists(CLL storage self, int n) internal constant returns (bool) { if (self.cll[HEAD][PREV] != HEAD || self.cll[HEAD][NEXT] != HEAD) return true; } // Returns the number of elements in the list function sizeOf(CLL storage self) internal constant returns (uint r) { int i = step(self, HEAD, NEXT); while (i != HEAD) { i = step(self, i, NEXT); r++; } return; } // Returns the links of a node as and array function getNode(CLL storage self, int n) internal constant returns (int[2]) { return [self.cll[n][PREV], self.cll[n][NEXT]]; } // Returns the link of a node `n` in direction `d`. function step(CLL storage self, int n, bool d) internal constant returns (int) { return self.cll[n][d]; } // Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d` function seek(CLL storage self, int a, int b, bool d) internal constant returns (int r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; } // Creates a bidirectional link between two nodes on direction `d` function stitch(CLL storage self, int a, int b, bool d) internal { self.cll[b][!d] = a; self.cll[a][d] = b; } // Insert node `b` beside existing node `a` in direction `d`. function insert (CLL storage self, int a, int b, bool d) internal { int c = self.cll[a][d]; stitch (self, a, b, d); stitch (self, b, c, d); } function remove(CLL storage self, int n) internal returns (int) { if (n == NULL) return; stitch(self, self.cll[n][PREV], self.cll[n][NEXT], NEXT); delete self.cll[n][PREV]; delete self.cll[n][NEXT]; return n; } function push(CLL storage self, int n, bool d) internal { insert(self, HEAD, n, d); } function pop(CLL storage self, bool d) internal returns (int) { return remove(self, step(self, HEAD, d)); } } /* End of LibCLLi */ /* file: ITT.sol ver: 0.3.6 updated:18-Nov-2016 author: Darryl Morris (o0ragman0o) email: o0ragman0o AT gmail.com An ERC20 compliant token with currency exchange functionality here called an 'Intrinsically Tradable Token' (ITT). This software 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 lesser General Public License for more details. <http://www.gnu.org/licenses/>. */ //pragma solidity ^0.4.0; //import "Base.sol"; //import "Math.sol"; //import "ERC20.sol"; //import "LibCLL.sol"; contract ITTInterface { using LibCLLu for LibCLLu.CLL; /* Constants */ string constant VERSION = "ITT 0.3.6\nERC20 0.2.3-o0ragman0o\nMath 0.0.1\nBase 0.1.1\n"; uint constant HEAD = 0; uint constant MINNUM = uint(1); // use only 128 bits of uint to prevent mul overflows. uint constant MAXNUM = 2**128; uint constant MINPRICE = uint(1); uint constant NEG = uint(-1); //2**256 - 1 bool constant PREV = false; bool constant NEXT = true; bool constant BID = false; bool constant ASK = true; // minimum gas required to prevent out of gas on 'take' loop uint constant MINGAS = 100000; // For staging and commiting trade details. This saves unneccessary state // change gas usage during multi order takes but does increase logic // complexity when encountering 'trade with self' orders struct TradeMessage { bool make; bool side; uint price; uint tradeAmount; uint balance; uint etherBalance; } /* State Valiables */ // To allow for trade halting by owner. bool public trading; // Mapping for ether ownership of accumulated deposits, sales and refunds. mapping (address => uint) etherBalance; // Orders are stored in circular linked list FIFO's which are mappings with // price as key and value as trader address. A trader can have only one // order open at each price. Reordering at that price will cancel the first // order and push the new one onto the back of the queue. mapping (uint => LibCLLu.CLL) orderFIFOs; // Order amounts are stored in a seperate lookup. The keys of this mapping // are `sha3` hashes of the price and trader address. // This mapping prevents more than one order at a particular price. mapping (bytes32 => uint) amounts; // The pricebook is a linked list holding keys to lookup the price FIFO's LibCLLu.CLL priceBook = orderFIFOs[0]; /* Events */ // Triggered on a make sell order event Ask (uint indexed price, uint amount, address indexed trader); // Triggered on a make buy order event Bid (uint indexed price, uint amount, address indexed trader); // Triggered on a filled order event Sale (uint indexed price, uint amount, address indexed buyer, address indexed seller); // Triggered when trading is started or halted event Trading(bool trading); /* Functions Public constant */ /// @notice Returns best bid or ask price. function spread(bool _side) public constant returns(uint); /// @notice Returns the order amount for trader `_trader` at '_price' /// @param _trader Address of trader /// @param _price Price of order function getAmount(uint _price, address _trader) public constant returns(uint); /// @notice Returns the collective order volume at a `_price`. /// @param _price FIFO for price. function getPriceVolume(uint _price) public constant returns (uint); /// @notice Returns an array of all prices and their volumes. /// @dev [even] indecies are the price. [odd] are the volume. [0] is the /// index of the spread. function getBook() public constant returns (uint[]); /* Functions Public non-constant*/ /// @notice Will buy `_amount` tokens at or below `_price` each. /// @param _bidPrice Highest price to bid. /// @param _amount The requested amount of tokens to buy. /// @param _make Value of true will make order if not filled. function buy (uint _bidPrice, uint _amount, bool _make) payable returns (bool); /// @notice Will sell `_amount` tokens at or above `_price` each. /// @param _askPrice Lowest price to ask. /// @param _amount The requested amount of tokens to buy. /// @param _make A value of true will make an order if not market filled. function sell (uint _askPrice, uint _amount, bool _make) external returns (bool); /// @notice Will withdraw `_ether` to your account. /// @param _ether The amount to withdraw function withdraw(uint _ether) external returns (bool success_); /// @notice Cancel order at `_price` /// @param _price The price at which the order was placed. function cancel(uint _price) external returns (bool); /// @notice Will set trading state to `_trading` /// @param _trading State to set trading to. function setTrading(bool _trading) external returns (bool); } /* Intrinsically Tradable Token code */ contract ITT is ERC20Token, ITTInterface { /* Structs */ /* Modifiers */ /// @dev Passes if token is currently trading modifier isTrading() { if (!trading) throw; _; } /// @dev Validate buy parameters modifier isValidBuy(uint _bidPrice, uint _amount) { if ((etherBalance[msg.sender] + msg.value) < (_amount * _bidPrice) || _amount == 0 || _amount > totalSupply || _bidPrice <= MINPRICE || _bidPrice >= MAXNUM) throw; // has insufficient ether. _; } /// @dev Validates sell parameters. Price must be larger than 1. modifier isValidSell(uint _askPrice, uint _amount) { if (_amount > balance[msg.sender] || _amount == 0 || _askPrice < MINPRICE || _askPrice > MAXNUM) throw; _; } /// @dev Validates ether balance modifier hasEther(address _member, uint _ether) { if (etherBalance[_member] < _ether) throw; _; } /// @dev Validates token balance modifier hasBalance(address _member, uint _amount) { if (balance[_member] < _amount) throw; _; } /* Functions */ function ITT( uint _totalSupply, uint8 _decimalPlaces, string _symbol, string _name ) ERC20Token( _totalSupply, _decimalPlaces, _symbol, _name ) { // setup pricebook and maximum spread. priceBook.cll[HEAD][PREV] = MINPRICE; priceBook.cll[MINPRICE][PREV] = MAXNUM; priceBook.cll[HEAD][NEXT] = MAXNUM; priceBook.cll[MAXNUM][NEXT] = MINPRICE; trading = true; balance[owner] = totalSupply; } /* Functions Getters */ function version() public constant returns(string) { return VERSION; } function etherBalanceOf(address _addr) public constant returns (uint) { return etherBalance[_addr]; } function spread(bool _side) public constant returns(uint) { return priceBook.step(HEAD, _side); } function getAmount(uint _price, address _trader) public constant returns(uint) { return amounts[sha3(_price, _trader)]; } function sizeOf(uint l) constant returns (uint s) { if(l == 0) return priceBook.sizeOf(); return orderFIFOs[l].sizeOf(); } function getPriceVolume(uint _price) public constant returns (uint v_) { uint n = orderFIFOs[_price].step(HEAD,NEXT); while (n != HEAD) { v_ += amounts[sha3(_price, address(n))]; n = orderFIFOs[_price].step(n, NEXT); } return; } function getBook() public constant returns (uint[]) { uint i; uint p = priceBook.step(MINNUM, NEXT); uint[] memory volumes = new uint[](priceBook.sizeOf() * 2 - 2); while (p < MAXNUM) { volumes[i++] = p; volumes[i++] = getPriceVolume(p); p = priceBook.step(p, NEXT); } return volumes; } function numOrdersOf(address _addr) public constant returns (uint) { uint c; uint p = MINNUM; while (p < MAXNUM) { if (amounts[sha3(p, _addr)] > 0) c++; p = priceBook.step(p, NEXT); } return c; } function getOpenOrdersOf(address _addr) public constant returns (uint[]) { uint i; uint c; uint p = MINNUM; uint[] memory open = new uint[](numOrdersOf(_addr)*2); p = MINNUM; while (p < MAXNUM) { if (amounts[sha3(p, _addr)] > 0) { open[i++] = p; open[i++] = amounts[sha3(p, _addr)]; } p = priceBook.step(p, NEXT); } return open; } function getNode(uint _list, uint _node) public constant returns(uint[2]) { return [orderFIFOs[_list].cll[_node][PREV], orderFIFOs[_list].cll[_node][NEXT]]; } /* Functions Public */ // Here non-constant public functions act as a security layer. They are re-entry // protected so cannot call each other. For this reason, they // are being used for parameter and enterance validation, while internal // functions manage the logic. This also allows for deriving contracts to // overload the public function with customised validations and not have to // worry about rewritting the logic. function buy (uint _bidPrice, uint _amount, bool _make) payable canEnter isTrading isValidBuy(_bidPrice, _amount) returns (bool) { trade(_bidPrice, _amount, BID, _make); return true; } function sell (uint _askPrice, uint _amount, bool _make) external canEnter isTrading isValidSell(_askPrice, _amount) returns (bool) { trade(_askPrice, _amount, ASK, _make); return true; } function withdraw(uint _ether) external canEnter hasEther(msg.sender, _ether) returns (bool success_) { etherBalance[msg.sender] -= _ether; safeSend(msg.sender, _ether); success_ = true; } function cancel(uint _price) external canEnter returns (bool) { TradeMessage memory tmsg; tmsg.price = _price; tmsg.balance = balance[msg.sender]; tmsg.etherBalance = etherBalance[msg.sender]; cancelIntl(tmsg); balance[msg.sender] = tmsg.balance; etherBalance[msg.sender] = tmsg.etherBalance; return true; } function setTrading(bool _trading) external onlyOwner canEnter returns (bool) { trading = _trading; Trading(true); return true; } /* Functions Internal */ // Internal functions handle this contract's logic. function trade (uint _price, uint _amount, bool _side, bool _make) internal { TradeMessage memory tmsg; tmsg.price = _price; tmsg.tradeAmount = _amount; tmsg.side = _side; tmsg.make = _make; // Cache state balances to memory and commit to storage only once after trade. tmsg.balance = balance[msg.sender]; tmsg.etherBalance = etherBalance[msg.sender] + msg.value; take(tmsg); make(tmsg); balance[msg.sender] = tmsg.balance; etherBalance[msg.sender] = tmsg.etherBalance; } function take (TradeMessage tmsg) internal { address maker; bytes32 orderHash; uint takeAmount; uint takeEther; // use of signed math on unsigned ints is intentional uint sign = tmsg.side ? uint(1) : uint(-1); uint bestPrice = spread(!tmsg.side); // Loop with available gas to take orders while ( tmsg.tradeAmount > 0 && cmpEq(tmsg.price, bestPrice, !tmsg.side) && msg.gas > MINGAS ) { maker = address(orderFIFOs[bestPrice].step(HEAD, NEXT)); orderHash = sha3(bestPrice, maker); if (tmsg.tradeAmount < amounts[orderHash]) { // Prepare to take partial order amounts[orderHash] = safeSub(amounts[orderHash], tmsg.tradeAmount); takeAmount = tmsg.tradeAmount; tmsg.tradeAmount = 0; } else { // Prepare to take full order takeAmount = amounts[orderHash]; tmsg.tradeAmount = safeSub(tmsg.tradeAmount, takeAmount); closeOrder(bestPrice, maker); } takeEther = safeMul(bestPrice, takeAmount); // signed multiply on uints is intentional and so safeMaths will // break here. Valid range for exit balances are 0..2**128 tmsg.etherBalance += takeEther * sign; tmsg.balance -= takeAmount * sign; if (tmsg.side) { // Sell to bidder if (msg.sender == maker) { // bidder is self tmsg.balance += takeAmount; } else { balance[maker] += takeAmount; } } else { // Buy from asker; if (msg.sender == maker) { // asker is self tmsg.etherBalance += takeEther; } else { etherBalance[maker] += takeEther; } } // prep for next order bestPrice = spread(!tmsg.side); Sale (bestPrice, takeAmount, msg.sender, maker); } } function make(TradeMessage tmsg) internal { bytes32 orderHash; if (tmsg.tradeAmount == 0 || !tmsg.make || msg.gas < MINGAS) return; orderHash = sha3(tmsg.price, msg.sender); if (amounts[orderHash] != 0) { // Cancel any pre-existing owned order at this price cancelIntl(tmsg); } if (!orderFIFOs[tmsg.price].exists()) { // Register price in pricebook priceBook.insert( priceBook.seek(HEAD, tmsg.price, tmsg.side), tmsg.price, !tmsg.side); } amounts[orderHash] = tmsg.tradeAmount; orderFIFOs[tmsg.price].push(uint(msg.sender), PREV); if (tmsg.side) { tmsg.balance -= tmsg.tradeAmount; Ask (tmsg.price, tmsg.tradeAmount, msg.sender); } else { tmsg.etherBalance -= tmsg.tradeAmount * tmsg.price; Bid (tmsg.price, tmsg.tradeAmount, msg.sender); } } function cancelIntl(TradeMessage tmsg) internal { uint amount = amounts[sha3(tmsg.price, msg.sender)]; if (amount == 0) return; if (tmsg.price > spread(BID)) tmsg.balance += amount; // was ask else tmsg.etherBalance += tmsg.price * amount; // was bid closeOrder(tmsg.price, msg.sender); } function closeOrder(uint _price, address _trader) internal { orderFIFOs[_price].remove(uint(_trader)); if (!orderFIFOs[_price].exists()) { priceBook.remove(_price); } delete amounts[sha3(_price, _trader)]; } }
To allow for trade halting by owner.
bool public trading;
1,055,327
[ 1, 774, 1699, 364, 18542, 19514, 1787, 635, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 1284, 7459, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.25; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @dev This contract manages the puzzles generation and hashes comparing */ contract PuzzleManager is Ownable { // Represents a generated puzzle. struct Puzzle { // The unique identifier for this puzzle. uint256 id; // The owner who generated this puzzle. address owner; // The original metrics associated to this puzzle. string originalMetrics; // The original hashed metrics associated to this puzzle. bytes32 originalHash; // The map of stored hashed metrics associated to this puzzle. mapping(address => bytes32) hashes; // Secure metrics bool secure; // Created by owner. // todo: remove that flag if not required by 3rd party puzzle generation. possible collisions bool createdByOwner; } // Internal generated puzzles. mapping (uint256 => Puzzle) private puzzles; // The next available id. uint256 private currentId = 0; mapping (address => bool) private validators; // banlist mapping (address => bool) private banList; // Events event PuzzleCreated(uint256 puzzleId, string uniqueId); /** * @dev Creates a new secure puzzle with given metrics * @param addr The owner of the puzzle * @param plainTextMetrics Metrics to push (string) * @param metricsHash The hash associated to the metrics * @param checkOwner If true, check if the sender is the owner of the contract * @param uniqueId Unique id * @return The ID of the new puzzle */ function createSecurePuzzle( address addr, string plainTextMetrics, bytes32 metricsHash, bool checkOwner, string uniqueId ) external returns (uint256) { require(banList[msg.sender] == false, "Player is banned"); if (checkOwner) { require(msg.sender == owner(), "Owner requirement failed"); } // We create the secure puzzle puzzles[currentId] = Puzzle({ id: currentId, owner: addr, originalMetrics: plainTextMetrics, originalHash: metricsHash, secure: true, createdByOwner: checkOwner }); // Increment the current id for the next puzzle. currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1; } /** * @dev Pushes secure metrics for the given puzzle * @param puzzleId The ID of a specific puzzle * @param metricsHash The hash associated to the metrics */ function pushSecureMetrics(uint256 puzzleId, bytes32 metricsHash) external { require(banList[msg.sender] == false, "Player is banned"); require(puzzles[puzzleId].secure, "Puzzle is not secure"); puzzles[puzzleId].hashes[msg.sender] = metricsHash; } /** * @dev Creates a new puzzle with given metrics * @param metrics The metrics * @param uniqueId A unique ID * @return The ID of the new puzzle */ function createPuzzle(string metrics, string uniqueId) external returns (uint256) { require(banList[msg.sender] == false, "Player is banned"); // We create the new puzzle puzzles[currentId] = Puzzle({ id: currentId, owner: msg.sender, originalMetrics: metrics, originalHash: keccak256(bytes(metrics)), secure: false, createdByOwner: false }); // Increment the current id for the next puzzle. currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1; } /** * @dev Pushes metrics for the given puzzle * @param puzzleId The ID of a specific puzzle * @param metrics String * @return Bool */ function pushMetrics(uint256 puzzleId, string metrics) external returns (bool) { require(banList[msg.sender] == false, "Player is banned"); puzzles[puzzleId].hashes[msg.sender] = keccak256(bytes(metrics)); return true; } /** * @dev Bans an address * @param user The address to ban */ function ban(address user) external onlyOwner() { banList[user] = true; } /** * @dev Unbans an address * @param user The address to unban */ function unban(address user) external onlyOwner() { banList[user] = false; } /** * @dev Compares the metrics associated to this address to the * original metrics, for the given puzzle id. * @param puzzleId The ID of a specific puzzle * @param byOwner bool * @return Bool */ function compareSecureMetrics(uint256 puzzleId, bool byOwner) external view returns (bool) { require(puzzles[puzzleId].secure, "Puzzle is not secure"); require(puzzles[puzzleId].createdByOwner == byOwner, "Puzzle invalid owner"); if (puzzles[puzzleId].originalHash == puzzles[puzzleId].hashes[msg.sender]) { return true; } return false; } /** * @dev Compares the metrics associated to this address to the * original metrics, for the given puzzle id. * @param puzzleId The ID of a specific puzzle * @return bool */ function compareMetrics(uint256 puzzleId) external view returns (bool) { if (puzzles[puzzleId].originalHash == puzzles[puzzleId].hashes[msg.sender]) { return true; } return false; } /** * @dev Returns the original metrics associated to a given puzzle id * @param puzzleId The ID of a specific puzzle * @return The original metrics of the specific puzzle */ function getPuzzleOriginalMetrics(uint256 puzzleId) external view returns (string) { return puzzles[puzzleId].originalMetrics; } /** * @dev Returns the hashed metrics associated to a given puzzle id * @param puzzleId The ID of a specific puzzle * @return The metrics */ function getPuzzleMetrics(uint256 puzzleId) external view returns (bytes) { bytes32 original = puzzles[puzzleId].originalHash; bytes32 current; if (msg.sender == puzzles[puzzleId].owner) { current = puzzles[puzzleId].originalHash; } else { current = puzzles[puzzleId].hashes[msg.sender]; } bytes memory result = new bytes(64); uint256 index1 = 0; uint256 index2 = 32; for (uint256 i = 0; i < 32; i += 1) { result[index1] = original[i]; result[index2] = current[i]; index1 += 1; index2 += 1; } return result; } }
Increment the current id for the next puzzle.
currentId += 1;
1,812,218
[ 1, 10798, 326, 783, 612, 364, 326, 1024, 293, 31550, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 783, 548, 1011, 404, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "../Governance/Claimable.sol"; import "./DarknodePaymentStore.sol"; import "./DarknodePayment.sol"; /// @notice The DarknodePaymentMigrator migrates unclaimed funds from the /// DarknodePayment contract. In a single transaction, it claims the store /// ownership from the DNP contract, migrates unclaimed fees and then returns /// the store ownership back to the DNP. contract DarknodePaymentMigrator is Claimable { DarknodePayment public dnp; address[] public tokens; constructor(DarknodePayment _dnp, address[] memory _tokens) public { Claimable.initialize(msg.sender); dnp = _dnp; tokens = _tokens; } function setTokens(address[] memory _tokens) public onlyOwner { tokens = _tokens; } function claimStoreOwnership() external { require(msg.sender == address(dnp), "Not darknode payment contract"); DarknodePaymentStore store = dnp.store(); store.claimOwnership(); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; uint256 unclaimed = store.availableBalance(token); if (unclaimed > 0) { store.incrementDarknodeBalance(address(0x0), token, unclaimed); store.transfer( address(0x0), token, unclaimed, _payableAddress(owner()) ); } } store.transferOwnership(address(dnp)); dnp.claimStoreOwnership(); require( store.owner() == address(dnp), "Store ownership not transferred back." ); } // Cast an address to a payable address function _payableAddress(address a) internal pure returns (address payable) { return address(uint160(address(a))); } }
Cast an address to a payable address
function _payableAddress(address a) internal pure returns (address payable) { return address(uint160(address(a))); }
2,496,732
[ 1, 9735, 392, 1758, 358, 279, 8843, 429, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10239, 429, 1887, 12, 2867, 279, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 2867, 8843, 429, 13, 203, 565, 288, 203, 3639, 327, 1758, 12, 11890, 16874, 12, 2867, 12, 69, 3719, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract IPhoenix { function getTotalLevels(address _user) external view returns(uint256){} } /** ______ __ ______ ______ ______ /\ == \ /\ \ /\ __ \ /\___ \ /\ ___\ \ \ __< \ \ \____ \ \ __ \ \/_/ /__ \ \ __\ \ \_____\ \ \_____\ \ \_\ \_\ /\_____\ \ \_____\ \/_____/ \/_____/ \/_/\/_/ \/_____/ \/_____/ */ contract Blaze is ERC20, Ownable { using SafeMath for uint256; mapping(address => uint) lastUpdate; mapping(address => bool) burnAddresses; mapping(address => uint) tokensOwed; IPhoenix[] public phoenixContracts; uint[] ratePerLevel; constructor() ERC20("Blaze", "BLAZE") { } /** __ __ __ ______ ______ ______ ______ ______ ______ __ ______ __ __ /\ \ /\ "-.\ \ /\__ _\ /\ ___\ /\ == \ /\ __ \ /\ ___\ /\__ _\ /\ \ /\ __ \ /\ "-.\ \ \ \ \ \ \ \-. \ \/_/\ \/ \ \ __\ \ \ __< \ \ __ \ \ \ \____ \/_/\ \/ \ \ \ \ \ \/\ \ \ \ \-. \ \ \_\ \ \_\\"\_\ \ \_\ \ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_____\ \ \_\ \ \_\ \ \_____\ \ \_\\"\_\ \/_/ \/_/ \/_/ \/_/ \/_____/ \/_/ /_/ \/_/\/_/ \/_____/ \/_/ \/_/ \/_____/ \/_/ \/_/ */ /* * @dev updates the tokens owed and the last time the user updated, called when leveling up a phoenix or minting * @dev _userAddress is the address of the user to update */ function updateTokens(address _userAddress) external { if (_userAddress != address(0)) { uint lastTime = lastUpdate[_userAddress]; uint currentTime = block.timestamp; lastUpdate[_userAddress] = currentTime; IPhoenix[] memory phoenix_contracts = phoenixContracts; uint[] memory ratePerLev = ratePerLevel; if(lastTime > 0) { uint claimable; for(uint i = 0; i < phoenix_contracts.length; i++) { claimable += phoenix_contracts[i].getTotalLevels(_userAddress).mul(ratePerLev[i]); } tokensOwed[_userAddress] += claimable.mul(currentTime - lastTime).div(86400); } } } /** * @dev called on token transfer, and updates the tokens owed and last update for each user involved in the transaction * @param _fromAddress is the address the token is being sent from * @param _toAddress is the address the token is being sent to */ function updateTransfer(address _fromAddress, address _toAddress) external { uint currentTime = block.timestamp; uint claimable; uint timeDifference; uint lastTime; IPhoenix[] memory phoenix_contracts = phoenixContracts; uint[] memory ratePerLev = ratePerLevel; if(_fromAddress != address(0)) { lastTime = lastUpdate[_fromAddress]; lastUpdate[_fromAddress] = currentTime; if(lastTime > 0) { claimable = 0; timeDifference = currentTime - lastTime; for(uint i = 0; i < phoenix_contracts.length; i++) { claimable += phoenix_contracts[i].getTotalLevels(_fromAddress).mul(ratePerLev[i]); } tokensOwed[_fromAddress] += claimable.mul(timeDifference).div(86400); } } if(_toAddress != address(0)) { lastTime = lastUpdate[_toAddress]; lastUpdate[_toAddress] = currentTime; if(lastTime > 0) { claimable = 0; timeDifference = currentTime - lastTime; for(uint i = 0; i < phoenix_contracts.length; i++) { claimable += phoenix_contracts[i].getTotalLevels(_toAddress).mul(ratePerLev[i]); } tokensOwed[_toAddress] += claimable.mul(timeDifference).div(86400); } } } /** * @dev claims tokens generated and mints into the senders wallet */ function claim() external { address sender = _msgSender(); uint lastUpdated = lastUpdate[sender]; uint time = block.timestamp; require(lastUpdated > 0, "No tokens to claim"); lastUpdate[sender] = time; uint unclaimed = getPendingTokens(sender, time - lastUpdated); if(tokensOwed[sender] > 0) { unclaimed += tokensOwed[sender]; tokensOwed[sender] = 0; } require(unclaimed > 0, "No tokens to claim"); _mint(sender, unclaimed); } /** * @dev burns the desired amount of tokens from the wallet, this can only be called by accepted addresses, prefers burning owed tokens over minted * @param _from is the address to burn the tokens from * @param _amount is the number of tokens attempting to be burned */ function burn(address _from, uint256 _amount) external { require(burnAddresses[_msgSender()] == true, "Don't have permission to call this function"); uint owed = tokensOwed[_from]; if(owed >= _amount) { tokensOwed[_from] -= _amount; return; } uint balance = balanceOf(_from); if(balance >= _amount) { _burn(_from, _amount); return; } if(balance + owed >= _amount) { tokensOwed[_from] = 0; _burn(_from, _amount - owed); return; } uint lastUpdated = lastUpdate[_from]; require(lastUpdated > 0, "User doesn't have enough blaze to complete this action"); uint time = block.timestamp; uint claimable = getPendingTokens(_from, time - lastUpdated); lastUpdate[_from] = time; if(claimable >= _amount) { tokensOwed[_from] += claimable - _amount; return; } if(claimable + owed >= _amount) { tokensOwed[_from] -= _amount - claimable; return; } if(balance + owed + claimable >= _amount) { tokensOwed[_from] = 0; _burn(_from, _amount - (owed + claimable)); return; } revert("User doesn't have enough blaze available to complete this action"); } /** ______ ______ ______ _____ /\ == \ /\ ___\ /\ __ \ /\ __-. \ \ __< \ \ __\ \ \ __ \ \ \ \/\ \ \ \_\ \_\ \ \_____\ \ \_\ \_\ \ \____- \/_/ /_/ \/_____/ \/_/\/_/ \/____/ */ /** * @dev returns the last time an address has updated with the contract * @param _userAddress is the user address that wants the know the time */ function lastUpdateTime(address _userAddress) public view returns(uint) { return lastUpdate[_userAddress]; } /** * @dev Gets the total tokens that are available to be claimed and minted for a given address * @param _userAddress is the address that the claimable tokens are calculated for */ function getClaimableTokens(address _userAddress) public view returns(uint) { return tokensOwed[_userAddress] + getPendingTokens(_userAddress); } /** * @dev returns the tokens accounted for but not minted for a given address * @param _userAddress is the address that wants to know whats owed */ function getTokensOwed(address _userAddress) public view returns(uint) { return tokensOwed[_userAddress]; } /** * @dev recieves the pending tokens yet to be accounted for * @param _userAddress is the address which the pending tokens are being calculated for * @param _timeDifference is the current time minus the last time the _userAddress was updated */ function getPendingTokens(address _userAddress, uint _timeDifference) public view returns(uint) { uint claimable; for(uint i = 0; i < phoenixContracts.length; i++) { claimable += phoenixContracts[i].getTotalLevels(_userAddress).mul(ratePerLevel[i]); } //multiply by the time in seconds, then divide by the number seconds in the day; return claimable.mul(_timeDifference).div(86400); } /** * @dev recieves the pending tokens yet to be accounted for, this function is called if the time difference since last update is unknown for the address * @param _userAddress is the address which the pending tokens are being calculated for */ function getPendingTokens(address _userAddress) public view returns(uint) { uint lastUpdated = lastUpdate[_userAddress]; if(lastUpdated == 0) { return 0; } return getPendingTokens(_userAddress, block.timestamp - lastUpdated); } /** ______ __ __ __ __ ______ ______ /\ __ \ /\ \ _ \ \ /\ "-.\ \ /\ ___\ /\ == \ \ \ \/\ \ \ \ \/ ".\ \ \ \ \-. \ \ \ __\ \ \ __< \ \_____\ \ \__/".~\_\ \ \_\\"\_\ \ \_____\ \ \_\ \_\ \/_____/ \/_/ \/_/ \/_/ \/_/ \/_____/ \/_/ /_/ */ /** * @dev Sets a phoenix contract where the phoenixs are capable of burning and generating tokens * @param _phoenixAddress is the address of the phoenix contract * @param _index is the index of where to set this information, either to add a new collection, or update an existing one * @param _ratePerLevel is the rate of token generation per phoenix level for this contract */ function setPhoenixContract(address _phoenixAddress, uint _index, uint _ratePerLevel) external onlyOwner { require(_index <= phoenixContracts.length, "index outside range"); if(phoenixContracts.length == _index) { phoenixContracts.push(IPhoenix(_phoenixAddress)); ratePerLevel.push(_ratePerLevel); } else { if(burnAddresses[address(phoenixContracts[_index])] == true) { burnAddresses[address(phoenixContracts[_index])] = false; } phoenixContracts[_index] = IPhoenix(_phoenixAddress); ratePerLevel[_index] = _ratePerLevel; } burnAddresses[_phoenixAddress] = true; } /** * @dev sets the addresss that are allowed to call the burn function * @param _burnAddress is the address being set * @param _value is to allow or remove burning permission */ function setBurnAddress(address _burnAddress, bool _value) external onlyOwner { burnAddresses[_burnAddress] = _value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* @dev burns the desired amount of tokens from the wallet, this can only be called by accepted addresses, prefers burning owed tokens over minted @param _from is the address to burn the tokens from @param _amount is the number of tokens attempting to be burned/
function burn(address _from, uint256 _amount) external { require(burnAddresses[_msgSender()] == true, "Don't have permission to call this function"); uint owed = tokensOwed[_from]; if(owed >= _amount) { tokensOwed[_from] -= _amount; return; } uint balance = balanceOf(_from); if(balance >= _amount) { _burn(_from, _amount); return; } if(balance + owed >= _amount) { tokensOwed[_from] = 0; _burn(_from, _amount - owed); return; } uint lastUpdated = lastUpdate[_from]; require(lastUpdated > 0, "User doesn't have enough blaze to complete this action"); uint time = block.timestamp; uint claimable = getPendingTokens(_from, time - lastUpdated); lastUpdate[_from] = time; if(claimable >= _amount) { tokensOwed[_from] += claimable - _amount; return; } if(claimable + owed >= _amount) { tokensOwed[_from] -= _amount - claimable; return; } if(balance + owed + claimable >= _amount) { tokensOwed[_from] = 0; _burn(_from, _amount - (owed + claimable)); return; } revert("User doesn't have enough blaze available to complete this action"); } /\ == \ /\ ___\ /\ __ \ /\ __-. \ \ __< \ \ __\ \ \ __ \ \ \ \/\ \ \ \_\ \_\ \ \_____\ \ \_\ \_\ \ \____- \/_/ /_/ \/_____/ \/_/\/_/ \/____/
2,548,163
[ 1, 70, 321, 87, 326, 6049, 3844, 434, 2430, 628, 326, 9230, 16, 333, 848, 1338, 506, 2566, 635, 8494, 6138, 16, 11307, 414, 18305, 310, 2523, 329, 2430, 1879, 312, 474, 329, 225, 389, 2080, 353, 326, 1758, 358, 18305, 326, 2430, 628, 225, 389, 8949, 353, 326, 1300, 434, 2430, 15600, 358, 506, 18305, 329, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 18305, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 8949, 13, 3903, 288, 203, 203, 202, 202, 6528, 12, 70, 321, 7148, 63, 67, 3576, 12021, 1435, 65, 422, 638, 16, 315, 22293, 1404, 1240, 4132, 358, 745, 333, 445, 8863, 203, 203, 202, 202, 11890, 2523, 329, 273, 2430, 3494, 329, 63, 67, 2080, 15533, 202, 203, 203, 202, 202, 430, 12, 543, 329, 1545, 389, 8949, 13, 288, 203, 1082, 202, 7860, 3494, 329, 63, 67, 2080, 65, 3947, 389, 8949, 31, 203, 1082, 202, 2463, 31, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 11013, 273, 11013, 951, 24899, 2080, 1769, 203, 203, 202, 202, 430, 12, 12296, 1545, 389, 8949, 13, 288, 203, 1082, 202, 67, 70, 321, 24899, 2080, 16, 389, 8949, 1769, 203, 1082, 202, 2463, 31, 203, 203, 202, 202, 97, 203, 203, 202, 202, 430, 12, 12296, 397, 2523, 329, 1545, 389, 8949, 13, 288, 203, 203, 1082, 202, 7860, 3494, 329, 63, 67, 2080, 65, 273, 374, 31, 203, 203, 1082, 202, 67, 70, 321, 24899, 2080, 16, 389, 8949, 300, 2523, 329, 1769, 203, 203, 1082, 202, 2463, 31, 203, 203, 202, 202, 97, 203, 203, 202, 202, 11890, 1142, 7381, 273, 1142, 1891, 63, 67, 2080, 15533, 203, 203, 202, 202, 6528, 12, 2722, 7381, 405, 374, 16, 315, 1299, 3302, 1404, 1240, 7304, 2811, 1561, 73, 358, 3912, 333, 1301, 8863, 203, 203, 202, 202, 11890, 813, 273, 1203, 18, 5508, 31, 203, 203, 202, 202, 11890, 7516, 429, 2 ]
pragma solidity ^0.4.21; // Generated by TokenGen and the Fabric Token platform. // https://tokengen.io // https://fabrictoken.io // File: contracts/library/SafeMath.sol /** * @title Safe Math * * @dev Library for safe mathematical operations. */ 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) { uint256 c = a / b; return c; } function minus(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function plus(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Token.sol /** * @dev The standard ERC20 Token contract base. */ contract ERC20Token { uint256 public totalSupply; /* shorthand for public function and a property */ function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: contracts/component/TokenSafe.sol /** * @title TokenSafe * * @dev Abstract contract that serves as a base for the token safes. It is a multi-group token safe, where each group * has it's own release time and multiple accounts with locked tokens. */ contract TokenSafe { using SafeMath for uint; // The ERC20 token contract. ERC20Token token; struct Group { // The release date for the locked tokens // Note: Unix timestamp fits in uint32, however block.timestamp is uint256 uint256 releaseTimestamp; // The total remaining tokens in the group. uint256 remaining; // The individual account token balances in the group. mapping (address => uint) balances; } // The groups of locked tokens mapping (uint8 => Group) public groups; /** * @dev The constructor. * * @param _token The address of the Fabric Token (fundraiser) contract. */ constructor(address _token) public { token = ERC20Token(_token); } /** * @dev The function initializes a group with a release date. * * @param _id Group identifying number. * @param _releaseTimestamp Unix timestamp of the time after which the tokens can be released */ function init(uint8 _id, uint _releaseTimestamp) internal { require(_releaseTimestamp > 0); Group storage group = groups[_id]; group.releaseTimestamp = _releaseTimestamp; } /** * @dev Add new account with locked token balance to the specified group id. * * @param _id Group identifying number. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function add(uint8 _id, address _account, uint _balance) internal { Group storage group = groups[_id]; group.balances[_account] = group.balances[_account].plus(_balance); group.remaining = group.remaining.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints of the group. * * @param _id Group identifying number. * @param _account The address of the account to be released. */ function release(uint8 _id, address _account) public { Group storage group = groups[_id]; require(now >= group.releaseTimestamp); uint tokens = group.balances[_account]; require(tokens > 0); group.balances[_account] = 0; group.remaining = group.remaining.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } } // File: contracts/token/StandardToken.sol /** * @title Standard Token * * @dev The standard abstract implementation of the ERC20 interface. */ contract StandardToken is ERC20Token { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev The constructor assigns the token name, symbols and decimals. */ constructor(string _name, string _symbol, uint8 _decimals) internal { name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev Get the balance of an address. * * @param _address The address which's balance will be checked. * * @return The current balance of the address. */ function balanceOf(address _address) public view returns (uint256 balance) { return balances[_address]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * * @param _owner The address which owns the funds allowed for spending by a third-party. * @param _spender The third-party address that is allowed to spend the tokens. * * @return The number of tokens available to `_spender` to be spent. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Give permission to `_spender` to spend `_value` number of tokens on your behalf. * E.g. You place a buy or sell order on an exchange and in that example, the * `_spender` address is the address of the contract the exchange created to add your token to their * website and you are `msg.sender`. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * * @return Whether the approval process was successful or not. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfers `_value` number of tokens to the `_to` address. * * @param _to The address of the recipient. * @param _value The number of tokens to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { executeTransfer(msg.sender, _to, _value); return true; } /** * @dev Allows another contract to spend tokens on behalf of the `_from` address and send them to the `_to` address. * * @param _from The address which approved you to spend tokens on their behalf. * @param _to The address where you want to send tokens. * @param _value The number of tokens to be sent. * * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].minus(_value); executeTransfer(_from, _to, _value); return true; } /** * @dev Internal function that this reused by the transfer functions */ function executeTransfer(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_value != 0 && _value <= balances[_from]); balances[_from] = balances[_from].minus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(_from, _to, _value); } } // File: contracts/token/MintableToken.sol /** * @title Mintable Token * * @dev Allows the creation of new tokens. */ contract MintableToken is StandardToken { /// @dev The only address allowed to mint coins address public minter; /// @dev Indicates whether the token is still mintable. bool public mintingDisabled = false; /** * @dev Event fired when minting is no longer allowed. */ event MintingDisabled(); /** * @dev Allows a function to be executed only if minting is still allowed. */ modifier canMint() { require(!mintingDisabled); _; } /** * @dev Allows a function to be called only by the minter */ modifier onlyMinter() { require(msg.sender == minter); _; } /** * @dev The constructor assigns the minter which is allowed to mind and disable minting */ constructor(address _minter) internal { minter = _minter; } /** * @dev Creates new `_value` number of tokens and sends them to the `_to` address. * * @param _to The address which will receive the freshly minted tokens. * @param _value The number of tokens that will be created. */ function mint(address _to, uint256 _value) public onlyMinter canMint { totalSupply = totalSupply.plus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(0x0, _to, _value); } /** * @dev Disable the minting of new tokens. Cannot be reversed. * * @return Whether or not the process was successful. */ function disableMinting() public onlyMinter canMint { mintingDisabled = true; emit MintingDisabled(); } } // File: contracts/token/BurnableToken.sol /** * @title Burnable Token * * @dev Allows tokens to be destroyed. */ contract BurnableToken is StandardToken { /** * @dev Event fired when tokens are burned. * * @param _from The address from which tokens will be removed. * @param _value The number of tokens to be destroyed. */ event Burn(address indexed _from, uint256 _value); /** * @dev Burnes `_value` number of tokens. * * @param _value The number of tokens that will be burned. */ function burn(uint256 _value) public { require(_value != 0); address burner = msg.sender; require(_value <= balances[burner]); balances[burner] = balances[burner].minus(_value); totalSupply = totalSupply.minus(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } // File: contracts/trait/HasOwner.sol /** * @title HasOwner * * @dev Allows for exclusive access to certain functionality. */ contract HasOwner { // The current owner. address public owner; // Conditionally the new owner. address public newOwner; /** * @dev The constructor. * * @param _owner The address of the owner. */ constructor(address _owner) public { owner = _owner; } /** * @dev Access control modifier that allows only the current owner to call the function. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev The event is fired when the current owner is changed. * * @param _oldOwner The address of the previous owner. * @param _newOwner The address of the new owner. */ event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner); /** * @dev Transfering the ownership is a two-step process, as we prepare * for the transfer by setting `newOwner` and requiring `newOwner` to accept * the transfer. This prevents accidental lock-out if something goes wrong * when passing the `newOwner` address. * * @param _newOwner The address of the proposed new owner. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev The `newOwner` finishes the ownership transfer process by accepting the * ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransfer(owner, newOwner); owner = newOwner; } } // File: contracts/token/PausableToken.sol /** * @title Pausable Token * * @dev Allows you to pause/unpause transfers of your token. **/ contract PausableToken is StandardToken, HasOwner { /// Indicates whether the token contract is paused or not. bool public paused = false; /** * @dev Event fired when the token contracts gets paused. */ event Pause(); /** * @dev Event fired when the token contracts gets unpaused. */ event Unpause(); /** * @dev Allows a function to be called only when the token contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Pauses the token contract. */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev Unpauses the token contract. */ function unpause() public onlyOwner { require(paused); paused = false; emit Unpause(); } /// Overrides of the standard token's functions to add the paused/unpaused functionality. function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/fundraiser/AbstractFundraiser.sol contract AbstractFundraiser { /// The ERC20 token contract. ERC20Token public token; /** * @dev The event fires every time a new buyer enters the fundraiser. * * @param _address The address of the buyer. * @param _ethers The number of ethers funded. * @param _tokens The number of tokens purchased. */ event FundsReceived(address indexed _address, uint _ethers, uint _tokens); /** * @dev The initialization method for the token * * @param _token The address of the token of the fundraiser */ function initializeFundraiserToken(address _token) internal { token = ERC20Token(_token); } /** * @dev The default function which is executed when someone sends funds to this contract address. */ function() public payable { receiveFunds(msg.sender, msg.value); } /** * @dev this overridable function returns the current conversion rate for the fundraiser */ function getConversionRate() public view returns (uint256); /** * @dev checks whether the fundraiser passed `endTime`. * * @return whether the fundraiser has ended. */ function hasEnded() public view returns (bool); /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal; /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view; /** * @dev this overridable function makes and handles tokens to buyers */ function handleTokens(address _address, uint256 _tokens) internal; /** * @dev this overridable function forwards the funds (if necessary) to a vault or directly to the beneficiary */ function handleFunds(address _address, uint256 _ethers) internal; } // File: contracts/fundraiser/BasicFundraiser.sol /** * @title Basic Fundraiser * * @dev An abstract contract that is a base for fundraisers. * It implements a generic procedure for handling received funds: * 1. Validates the transaciton preconditions * 2. Calculates the amount of tokens based on the conversion rate. * 3. Delegate the handling of the tokens (mint, transfer or conjure) * 4. Delegate the handling of the funds * 5. Emit event for received funds */ contract BasicFundraiser is HasOwner, AbstractFundraiser { using SafeMath for uint256; // The number of decimals for the token. uint8 constant DECIMALS = 18; // Enforced // Decimal factor for multiplication purposes. uint256 constant DECIMALS_FACTOR = 10 ** uint256(DECIMALS); // The start time of the fundraiser - Unix timestamp. uint256 public startTime; // The end time of the fundraiser - Unix timestamp. uint256 public endTime; // The address where funds collected will be sent. address public beneficiary; // The conversion rate with decimals difference adjustment, // When converion rate is lower than 1 (inversed), the function calculateTokens() should use division uint256 public conversionRate; // The total amount of ether raised. uint256 public totalRaised; /** * @dev The event fires when the number of token conversion rate has changed. * * @param _conversionRate The new number of tokens per 1 ether. */ event ConversionRateChanged(uint _conversionRate); /** * @dev The basic fundraiser initialization method. * * @param _startTime The start time of the fundraiser - Unix timestamp. * @param _endTime The end time of the fundraiser - Unix timestamp. * @param _conversionRate The number of tokens create for 1 ETH funded. * @param _beneficiary The address which will receive the funds gathered by the fundraiser. */ function initializeBasicFundraiser( uint256 _startTime, uint256 _endTime, uint256 _conversionRate, address _beneficiary ) internal { require(_endTime >= _startTime); require(_conversionRate > 0); require(_beneficiary != address(0)); startTime = _startTime; endTime = _endTime; conversionRate = _conversionRate; beneficiary = _beneficiary; } /** * @dev Sets the new conversion rate * * @param _conversionRate New conversion rate */ function setConversionRate(uint256 _conversionRate) public onlyOwner { require(_conversionRate > 0); conversionRate = _conversionRate; emit ConversionRateChanged(_conversionRate); } /** * @dev Sets The beneficiary of the fundraiser. * * @param _beneficiary The address of the beneficiary. */ function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != address(0)); beneficiary = _beneficiary; } /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal { validateTransaction(); uint256 tokens = calculateTokens(_amount); require(tokens > 0); totalRaised = totalRaised.plus(_amount); handleTokens(_address, tokens); handleFunds(_address, _amount); emit FundsReceived(_address, msg.value, tokens); } /** * @dev this overridable function returns the current conversion rate multiplied by the conversion rate factor */ function getConversionRate() public view returns (uint256) { return conversionRate; } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { tokens = _amount.mul(getConversionRate()); } /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view { require(msg.value != 0); require(now >= startTime && now < endTime); } /** * @dev checks whether the fundraiser passed `endtime`. * * @return whether the fundraiser is passed its deadline or not. */ function hasEnded() public view returns (bool) { return now >= endTime; } } // File: contracts/token/StandardMintableToken.sol contract StandardMintableToken is MintableToken { constructor(address _minter, string _name, string _symbol, uint8 _decimals) StandardToken(_name, _symbol, _decimals) MintableToken(_minter) public { } } // File: contracts/fundraiser/MintableTokenFundraiser.sol /** * @title Fundraiser With Mintable Token */ contract MintableTokenFundraiser is BasicFundraiser { /** * @dev The initialization method that creates a new mintable token. * * @param _name Token name * @param _symbol Token symbol * @param _decimals Token decimals */ function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal { token = new StandardMintableToken( address(this), // The fundraiser is the token minter _name, _symbol, _decimals ); } /** * @dev Mint the specific amount tokens */ function handleTokens(address _address, uint256 _tokens) internal { MintableToken(token).mint(_address, _tokens); } } // File: contracts/fundraiser/IndividualCapsFundraiser.sol /** * @title Fundraiser with individual caps * * @dev Allows you to set a hard cap on your fundraiser. */ contract IndividualCapsFundraiser is BasicFundraiser { uint256 public individualMinCap; uint256 public individualMaxCap; uint256 public individualMaxCapTokens; event IndividualMinCapChanged(uint256 _individualMinCap); event IndividualMaxCapTokensChanged(uint256 _individualMaxCapTokens); /** * @dev The initialization method. * * @param _individualMinCap The minimum amount of ether contribution per address. * @param _individualMaxCap The maximum amount of ether contribution per address. */ function initializeIndividualCapsFundraiser(uint256 _individualMinCap, uint256 _individualMaxCap) internal { individualMinCap = _individualMinCap; individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; } function setConversionRate(uint256 _conversionRate) public onlyOwner { super.setConversionRate(_conversionRate); if (individualMaxCap == 0) { return; } individualMaxCapTokens = individualMaxCap * _conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } function setIndividualMinCap(uint256 _individualMinCap) public onlyOwner { individualMinCap = _individualMinCap; emit IndividualMinCapChanged(individualMinCap); } function setIndividualMaxCap(uint256 _individualMaxCap) public onlyOwner { individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } /** * @dev Extends the transaction validation to check if the value this higher than the minumum cap. */ function validateTransaction() internal view { super.validateTransaction(); require(msg.value >= individualMinCap); } /** * @dev We validate the new amount doesn't surpass maximum contribution cap */ function handleTokens(address _address, uint256 _tokens) internal { require(individualMaxCapTokens == 0 || token.balanceOf(_address).plus(_tokens) <= individualMaxCapTokens); super.handleTokens(_address, _tokens); } } // File: contracts/fundraiser/GasPriceLimitFundraiser.sol /** * @title GasPriceLimitFundraiser * * @dev This fundraiser allows to set gas price limit for the participants in the fundraiser */ contract GasPriceLimitFundraiser is HasOwner, BasicFundraiser { uint256 public gasPriceLimit; event GasPriceLimitChanged(uint256 gasPriceLimit); /** * @dev This function puts the initial gas limit */ function initializeGasPriceLimitFundraiser(uint256 _gasPriceLimit) internal { gasPriceLimit = _gasPriceLimit; } /** * @dev This function allows the owner to change the gas limit any time during the fundraiser */ function changeGasPriceLimit(uint256 _gasPriceLimit) onlyOwner() public { gasPriceLimit = _gasPriceLimit; emit GasPriceLimitChanged(_gasPriceLimit); } /** * @dev The transaction is valid if the gas price limit is lifted-off or the transaction meets the requirement */ function validateTransaction() internal view { require(gasPriceLimit == 0 || tx.gasprice <= gasPriceLimit); return super.validateTransaction(); } } // File: contracts/fundraiser/ForwardFundsFundraiser.sol /** * @title Forward Funds to Beneficiary Fundraiser * * @dev This contract forwards the funds received to the beneficiary. */ contract ForwardFundsFundraiser is BasicFundraiser { /** * @dev Forward funds directly to beneficiary */ function handleFunds(address, uint256 _ethers) internal { // Forward the funds directly to the beneficiary beneficiary.transfer(_ethers); } } // File: contracts/fundraiser/TieredFundraiser.sol /** * @title TieredFundraiser * * @dev A fundraiser that improves the base conversion precision to allow percent bonuses */ contract TieredFundraiser is BasicFundraiser { // Conversion rate factor for better precision. uint256 constant CONVERSION_RATE_FACTOR = 100; /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { return super.getConversionRate().mul(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { return super.calculateTokens(_amount).div(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function returns the current conversion rate factor */ function getConversionRateFactor() public pure returns (uint256) { return CONVERSION_RATE_FACTOR; } } // File: contracts/Fundraiser.sol /** * @title AdultXToken */ contract AdultXToken is MintableToken, BurnableToken, PausableToken { constructor(address _owner, address _minter) StandardToken( "Adult X Token", // Token name "ADUX", // Token symbol 18 // Token decimals ) HasOwner(_owner) MintableToken(_minter) public { } } /** * @title AdultXTokenSafe */ contract AdultXTokenSafe is TokenSafe { constructor(address _token) TokenSafe(_token) public { // Group "Airdrop" init( 1, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 1, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); // Group "Marketing" init( 2, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 2, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 100000000000000000000000000 // Allocated tokens ); // Group "Team and Partners" init( 3, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 3, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); } } /** * @title AdultXTokenFundraiser */ contract AdultXTokenFundraiser is MintableTokenFundraiser, IndividualCapsFundraiser, ForwardFundsFundraiser, TieredFundraiser, GasPriceLimitFundraiser { AdultXTokenSafe public tokenSafe; constructor() HasOwner(msg.sender) public { token = new AdultXToken( msg.sender, // Owner address(this) // The fundraiser is the minter ); tokenSafe = new AdultXTokenSafe(token); MintableToken(token).mint(address(tokenSafe), 200000000000000000000000000); initializeBasicFundraiser( 1543795140, // Start date = 2018-12-02 23:59 UTC 1609459140, // End date = 2020-12-31 23:59 UTC 6000, // Conversion rate = 6000 ADUX per 1 ether 0x1f98908f6857de3227fb735fACa75CCD5b9403c5 // Beneficiary ); initializeIndividualCapsFundraiser( (0.1 ether), // Minimum contribution (0 ether) // Maximum individual cap ); initializeGasPriceLimitFundraiser( 0 // Gas price limit in wei ); } /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { uint256 rate = super.getConversionRate(); if (now >= 1543795140 && now < 1544918340) return rate.mul(125).div(100); if (now >= 1544918340 && now < 1546300740) return rate.mul(120).div(100); if (now >= 1546300740 && now < 1547855940) return rate.mul(110).div(100); return rate; } /** * @dev Fundraiser with mintable token allows the owner to mint through the Fundraiser contract */ function mint(address _to, uint256 _value) public onlyOwner { MintableToken(token).mint(_to, _value); } /** * @dev Irreversibly disable minting */ function disableMinting() public onlyOwner { MintableToken(token).disableMinting(); } }
* @dev checks whether the fundraiser passed `endtime`. @return whether the fundraiser is passed its deadline or not./
function hasEnded() public view returns (bool) { return now >= endTime; }
1,777,916
[ 1, 12366, 2856, 326, 284, 1074, 354, 15914, 2275, 1375, 409, 957, 8338, 327, 2856, 326, 284, 1074, 354, 15914, 353, 2275, 2097, 14096, 578, 486, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 711, 28362, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2037, 1545, 13859, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3B3812BB9f6151bEb6fa10783F1ae848a77a0d46/sources/CollateralErc20.sol
scale up before entering the system.
function deposit( address borrower, uint id, uint amount ) external { require(amount <= IERC20(underlyingContract).allowance(msg.sender, address(this)), "Allowance not high enough"); IERC20(underlyingContract).transferFrom(msg.sender, address(this), amount); uint scaledAmount = scaleUpCollateral(amount); depositInternal(borrower, id, scaledAmount); }
2,762,253
[ 1, 5864, 731, 1865, 19014, 326, 2619, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 1758, 29759, 264, 16, 203, 3639, 2254, 612, 16, 203, 3639, 2254, 3844, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 8949, 1648, 467, 654, 39, 3462, 12, 9341, 6291, 8924, 2934, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 13, 3631, 315, 7009, 1359, 486, 3551, 7304, 8863, 203, 203, 3639, 467, 654, 39, 3462, 12, 9341, 6291, 8924, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 203, 3639, 2254, 12304, 6275, 273, 3159, 1211, 13535, 2045, 287, 12, 8949, 1769, 203, 203, 3639, 443, 1724, 3061, 12, 70, 15318, 264, 16, 612, 16, 12304, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Administration.sol"; contract DataBank is Administration { address[] paymentTokens; uint256 weekPeriod = 604800; uint256 monthPeriod = 2592000; enum PaymentStatus{NOTDUE, DUE, OVERDUE} mapping(uint256 => Renter) internal RENTERS; // Renter identifier mapping(uint256 => Rentee) internal RENTEES; // Renter identifier mapping(uint256 => Property) internal PROPERTIES; // Property identifier mapping(uint256 => Property) internal ownedProperties; // 0 index of owned property mapping(uint256 => mapping(PaymentStatus => Property)) internal _propertyRentStatus; // status of current month's rent for user mapping(uint256 => mapping(PaymentStatus => Renter)) internal _renterRentStatus; // status of current month's rent struct Renter { address[] renterWallets; // array of user wallets address[] admins; // array of admin addresses uint256 arrears; // rent owed uint256 rent; // rent amount uint256 weeksMissed; // how many weeks in arrears uint256 renterID; // renter identifier uint256 propertyID; // Property Identifier bool inDebt; // Yes or No, quick identifier bool isDeleted; // Yes or No, has the Renter been removed PaymentStatus paymentStatus; } struct Rentee { address[] renteeWallets; // array of rentee wallets address[] admins; // array of admin addresses uint256[] ownedProperties; // owned properties uint256 monthlyRentDue; // amount due each month = property.rent * rent / 12 * ownedProperties uint256 arrearsOwed; // arrears owed = renter.weeksMissed * rent(weekPeriod).propertyID uint256 renteeID; // Rentee identifier bool isDeleted; // Yes or No, has the Rentee been removed } struct Property { string identifier; // house name or number string streetName; // street name string postcode; // zip code uint256 rent; // monthly rent amount uint256 renteeID; // Rentee Identifier uint256 renterID; // Renter Identifier uint256 propertyID; // Property Identifier address[] admins; // array of admin addresses bool inDefault; // Yes or No, quick identifier bool isDeleted; // Yes or No, has the property been removed PaymentStatus paymentStatus; } }
house name or number
string identifier;
7,230,297
[ 1, 13028, 508, 578, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 2756, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity =0.8.0; // SPDX-License-Identifier: MIT // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } /** * @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); } } /** * @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); } /** * @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; } } /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } /// @title Locked /// @dev Smart contract to enable locking and unlocking of token holders. contract Locked is AccessControl { mapping (address => bool) public lockedList; event AddedLock(address user); event RemovedLock(address user); // Create a new role identifier for the controller role bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); modifier isController { require(hasRole(CONTROLLER_ROLE, msg.sender), "Locked::isController - Caller is not a controller"); _; } modifier isMinter { require(hasRole(MINTER_ROLE, msg.sender), "Locked::isMinter - Caller is not a minter"); _; } /// @dev terminate transaction if any of the participants is locked /// @param _from - user initiating process /// @param _to - user involved in process modifier isNotLocked(address _from, address _to) { if (!hasRole(DEFAULT_ADMIN_ROLE, _from)){ // allow contract admin on sending tokens even if recipient is locked require(!lockedList[_from], "Locked::isNotLocked - User is locked"); require(!lockedList[_to], "Locked::isNotLocked - User is locked"); } _; } /// @dev check if user has been locked /// @param _user - usr to check /// @return true or false function isLocked(address _user) public view returns (bool) { return lockedList[_user]; } /// @dev add user to lock /// @param _user to lock function addLock (address _user) public isController() { _addLock(_user); } function addLockMultiple(address[] memory _users) public isController() { uint256 length = _users.length; require(length <= 256, "Locked-addLockMultiple: List too long"); for (uint256 i = 0; i < length; i++) { _addLock(_users[i]); } } /// @dev unlock user /// @param _user - user to unlock function removeLock (address _user) isController() public { _removeLock(_user); } /// @dev add user to lock for internal needs /// @param _user to lock function _addLock(address _user) internal { lockedList[_user] = true; emit AddedLock(_user); } /// @dev unlock user for internal needs /// @param _user - user to unlock function _removeLock (address _user) internal { lockedList[_user] = false; emit RemovedLock(_user); } } pragma experimental ABIEncoderV2; contract AuditToken is Locked, ERC20, ERC20Burnable{ /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice 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); uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 250000000 * (10**uint256(DECIMALS)); address public migrationAgent; uint256 public totalMigrated; /// @dev Constructor that gives an account all initial tokens. constructor(address account) ERC20("Auditchain", "AUDT") { require(account != address(0), "AuditToken:constructor - Address can't be 0"); _mint(account, INITIAL_SUPPLY); _setupRole(DEFAULT_ADMIN_ROLE, account); } /// @dev prevent accidental sending of tokens to this token contract /// @param _self - address of this contract modifier notSelf(address _self) { require( _self != address(this), "You are trying to send tokens to this token contract" ); _; } /// @notice Overwrite parent implementation to add locked verification, notSelf modifiers and call to moveDelegates function transfer(address to, uint256 value) public override isNotLocked(msg.sender, to) notSelf(to) returns (bool) { _moveDelegates(delegates[msg.sender], delegates[to], uint96(value)); return super.transfer(to, value); } /// @notice Overwrite parent implementation to add locked verification, notSelf modifiers and call to moveDelegates function transferFrom( address from, address to, uint256 value ) public override isNotLocked(from, to) notSelf(to) returns (bool) { _moveDelegates(delegates[from], delegates[to], uint96(value)); return super.transferFrom(from, to, value); } /// @dev Function to mint tokens /// @param to address to which new minted tokens are sent /// @param amount of tokens to send /// @return A boolean that indicates if the operation was successful. function mint(address to, uint256 amount) public isMinter() returns (bool) { _mint(to, amount); return true; } /// @notice Overwrite parent implementation to add locked verification function burn (uint256 amount) public override isNotLocked(msg.sender, msg.sender) { super.burn(amount); } /// @notice Overwrite parent implementation to add locked verification function burnFrom (address user, uint256 amount) public override isNotLocked(msg.sender, msg.sender) { super.burnFrom(user, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "auditToken::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]; uint96 delegatorBalance = uint96(balanceOf(delegator)); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "auditToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "auditToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "auditToken::_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 add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // @note this contract can be inherited by Sale contract // control release of tokens through even time release based on the inputted duration time interval contract Vesting { using SafeMath for uint256; using SafeERC20 for AuditToken; struct TokenHolder { uint256 tokensToSend; // amount of tokens sent uint256 releasedAmount; // amount released through vesting schedule bool revoked; // true if right to continue vesting is revoked bool notStaked; } event VestedPortionReleased(uint256 amount, address user); event StakingRewardsReleased(uint256 amount, address user); event MemberFunded(address beneficiary, uint256 amount, bool notStaked); event VestingFunded(uint256 amount); event Revoke(address user); event Reinstate(address user); uint256 public cliff; // time in when vesting should begin uint256 public startCountDown; // time when countdown starts uint256 public duration; // duration of period in which vesting takes place AuditToken internal _token; // token contract containing tokens mapping(address => TokenHolder) public tokenHolders; //tokenHolder list uint256 public stakingRatio; // percentage with two extra 0s to accommodate for 2 decimal places. e.g. 13.33%-> 1333, 100% -> 10000 uint256 public constant CLIFF = 60 * 60 * 24 * 14; // 14 days uint256 public constant DURATION = 60 * 60 * 24 * 366; // 366 days // uint256 public constant STAKING_RATIO = 50; address public admin; uint256 public totalRedeemable; /** * @notice Specify address of token contract for case with no white list required * @param _admin address of person who can revoke vesting for the user * @param _tokenAddress {address} address of token contract */ constructor (address _admin, address _tokenAddress, uint256 _stakingRatio) { require(_tokenAddress != address(0), "Vesting:constructor - token address can't be 0"); require(_admin != address(0), "Vesting:constructor - admin address can't be 0"); require(_stakingRatio !=0, "Vesting:constructor - staking ratio can't be 0"); duration = DURATION; startCountDown = block.timestamp; cliff = startCountDown.add(CLIFF); _token = AuditToken(_tokenAddress); admin = _admin; stakingRatio = _stakingRatio; } /** * @dev to check if user is authorized to do admin actions */ modifier isAdmin { require(msg.sender == admin, "Sale:isAdmin - Caller is not an operator"); _; } // @notice To return vesting schedule function returnVestingSchedule() external view returns (uint, uint, uint, uint) { return (duration, cliff, startCountDown, block.timestamp); } /** @dev calculates rewards based on released amount * @param user - user whose rewards are being calculated * @return amount of tokens for reward. Excludes team members who are not part of reward program. */ function calculateRewardsTotal(address user) public view returns (uint256) { TokenHolder memory tokenHolder = tokenHolders[user]; if (!tokenHolder.notStaked ) return tokenHolder.tokensToSend.sub(tokenHolder.releasedAmount).mul(stakingRatio).div(10000); else return 0; } /** * @dev allocate tokens to early investor or team member * @param beneficiary - user who gets tokens allocated * @param amount - amount of tokens being allocated * @param notStaked - flag if user is eligible for vesting rewards */ function allocateUser(address beneficiary, uint256 amount, bool notStaked) internal { require(address(beneficiary) != address(0), "Staking:allocateUser - beneficiary can't be the zero address"); require(amount != 0, "Vesting:allocateUser Amount can't be 0"); TokenHolder storage tokenHolder = tokenHolders[beneficiary]; tokenHolder.tokensToSend += amount; tokenHolder.notStaked = notStaked; totalRedeemable = totalRedeemable.add(amount); emit MemberFunded(beneficiary, amount, notStaked); } /** * @dev allocate tokens to early investor or team member in a batch * @param beneficiary - users who gets tokens allocated * @param amount - amounts of tokens being allocated * @param notStaked - flags if user is eligible for vesting rewards */ function allocateUserMultiple(address[] memory beneficiary, uint256[] memory amount, bool[] memory notStaked) public isAdmin() { uint256 length = beneficiary.length; require(length <= 346, "Vesting-allocateUserMultiple: List too long"); for (uint256 i = 0; i < length; i++) { allocateUser(beneficiary[i], amount[i], notStaked[i]); } } /** * @dev owner can revoke access to continue vesting of tokens * @param _user {address} of user to revoke their right to vesting */ function revoke(address _user) public isAdmin(){ TokenHolder storage tokenHolder = tokenHolders[_user]; tokenHolder.revoked = true; emit Revoke(_user); } /** * @dev owner can reinstate access to continue vesting of tokens * @param _user {address} of user to reinstate their right to vesting */ function reinstate(address _user) public isAdmin(){ TokenHolder storage tokenHolder = tokenHolders[_user]; tokenHolder.revoked = false; emit Reinstate(_user); } /** * @dev Show amount of token still available for vesting * @return amount {uint} tokens still available for vesting */ function vestedAmountAvailable() public view returns (uint256 amount) { TokenHolder memory tokenHolder = tokenHolders[msg.sender]; uint tokensToRelease = vestedAmount(tokenHolder.tokensToSend); return tokensToRelease.sub(tokenHolder.releasedAmount); } // @notice Transfers vested available tokens to beneficiary function release() public { TokenHolder storage tokenHolder = tokenHolders[msg.sender]; require(!tokenHolder.revoked, "Vesting:release - Your vesting has been revoked."); require( tokenHolder.releasedAmount <= tokenHolder.tokensToSend, "Vesting:release - You have already claimed all your tokens."); if (startCountDown.add(DURATION) < block.timestamp && !tokenHolder.notStaked ) claimStake(); uint tokensToRelease = vestedAmount(tokenHolder.tokensToSend); require(tokensToRelease > 0, "Vesting:release - Cliff is still in effect" ); uint currentTokenToRelease = tokensToRelease - tokenHolder.releasedAmount; tokenHolder.releasedAmount += currentTokenToRelease; _token.mint(msg.sender, currentTokenToRelease); emit VestedPortionReleased(currentTokenToRelease, msg.sender); } /** * @notice this function will determine vested amount * @param _totalBalance {uint} total balance of tokens assigned to this user * @return {uint} amount of tokens available to transfer */ function vestedAmount(uint _totalBalance) public view returns (uint) { if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= startCountDown.add(duration)) { return _totalBalance; } else { return _totalBalance.mul(block.timestamp.sub(startCountDown)) / duration; } } /** * @dev to release vesting rewards */ function claimStake() internal { require(startCountDown.add(DURATION) < block.timestamp, "Vesting:claimStake - Stake can be claimed only after vesting expired"); uint256 reward = calculateRewardsTotal(msg.sender); _token.mint(msg.sender, reward); emit StakingRewardsReleased(reward, msg.sender); } }
token contract containing tokens
AuditToken internal _token;
6,027,602
[ 1, 2316, 6835, 4191, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 12975, 1345, 225, 2713, 225, 389, 2316, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./Douya.sol"; contract TokenBank { address public owner; Douya public douya; address[] public stakers; mapping(address => uint256) public stakingBalance; mapping(address => bool) public hasStaked; mapping(address => bool) public isStaking; constructor(address _douya) { douya = Douya(_douya); owner = msg.sender; } function stakeTokens(uint256 _amount) public { // Require amount greater than 0 require(_amount > 0, "amount cannot be 0"); // Trasnfer Mock Dai tokens to this contract for staking douya.transferFrom(msg.sender, address(this), _amount); // Update staking balance // 这里要防止溢出,所以加之后必须检查,需要加之后的前必须大于之前的 require( stakingBalance[msg.sender] + _amount > stakingBalance[msg.sender], "new value is smaller than before." ); stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; // Add user to stakers array *only* if they haven't staked already if (!hasStaked[msg.sender]) { stakers.push(msg.sender); } // Update staking status isStaking[msg.sender] = true; hasStaked[msg.sender] = true; } // Unstaking Tokens (Withdraw) function unstakeTokens() public { // Fetch staking balance uint256 balance = stakingBalance[msg.sender]; // Require amount greater than 0 require(balance > 0, "staking balance cannot be 0"); // Transfer Mock Dai tokens to this contract for staking douya.transfer(msg.sender, balance); // Reset staking balance stakingBalance[msg.sender] = 0; // Update staking status isStaking[msg.sender] = false; } // Issuing Tokens function issueTokens() public { // Only owner can call this function require(msg.sender == owner, "caller must be the owner"); // Issue tokens to all stakers for (uint256 i = 0; i < stakers.length; i++) { address recipient = stakers[i]; uint256 balance = stakingBalance[recipient]; if (balance > 0) { douya.transfer(recipient, balance / 10); } } } }
Require amount greater than 0 Trasnfer Mock Dai tokens to this contract for staking Update staking balance 这里要防止溢出,所以加之后必须检查,需要加之后的前必须大于之前的 Add user to stakers array *only* if they haven't staked already
function stakeTokens(uint256 _amount) public { require(_amount > 0, "amount cannot be 0"); douya.transferFrom(msg.sender, address(this), _amount); require( stakingBalance[msg.sender] + _amount > stakingBalance[msg.sender], "new value is smaller than before." ); stakingBalance[msg.sender] = stakingBalance[msg.sender] + _amount; if (!hasStaked[msg.sender]) { stakers.push(msg.sender); } hasStaked[msg.sender] = true; }
12,812,884
[ 1, 8115, 3844, 6802, 2353, 374, 840, 31432, 586, 7867, 463, 10658, 2430, 358, 333, 6835, 364, 384, 6159, 2315, 384, 6159, 11013, 225, 169, 128, 252, 170, 234, 239, 169, 104, 228, 170, 251, 115, 167, 260, 100, 167, 123, 100, 166, 234, 123, 176, 125, 239, 167, 236, 227, 165, 124, 103, 166, 237, 259, 165, 122, 238, 166, 243, 241, 166, 128, 232, 170, 99, 124, 167, 101, 227, 167, 258, 103, 176, 125, 239, 170, 255, 227, 169, 104, 228, 166, 237, 259, 165, 122, 238, 166, 243, 241, 168, 253, 231, 166, 236, 240, 166, 128, 232, 170, 99, 124, 166, 102, 105, 165, 123, 241, 165, 122, 238, 166, 236, 240, 168, 253, 231, 1436, 729, 358, 384, 581, 414, 526, 1338, 309, 2898, 15032, 1404, 384, 9477, 1818, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 384, 911, 5157, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 8949, 2780, 506, 374, 8863, 203, 203, 3639, 741, 9835, 69, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 397, 389, 8949, 405, 384, 6159, 13937, 63, 3576, 18, 15330, 6487, 203, 5411, 315, 2704, 460, 353, 10648, 2353, 1865, 1199, 203, 3639, 11272, 203, 3639, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 273, 384, 6159, 13937, 63, 3576, 18, 15330, 65, 397, 389, 8949, 31, 203, 203, 3639, 309, 16051, 5332, 510, 9477, 63, 3576, 18, 15330, 5717, 288, 203, 5411, 384, 581, 414, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 289, 203, 203, 3639, 711, 510, 9477, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x3e516824a408c7029c3f870510d59442143c2db9 //Contract name: Version //Balance: 0 Ether //Verification Date: 2/23/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(uint holdings, uint price, uint decimals); event RequestUpdated(uint id); event Invested(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event SpendingApproved(address onConsigned, address ofAsset, uint amount); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event OrderUpdated(uint id); event LogError(uint ERROR_CODE); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, bool isNativeAsset) external; function requestRedemption(uint shareQuantity, uint receiveQuantity, bool isNativeAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment() external; function disableInvestment() external; function enableRedemption() external; function disableRedemption() external; function shutDown() external; // Managing by Manager function makeOrder(uint exchangeId, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity) external; function takeOrder(uint exchangeId, uint id, uint quantity) external; function cancelOrder(uint exchangeId, uint id) external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastOrderId() view returns (uint); function getLastRequestId() view returns (uint); function getNameHash() view returns (bytes32); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS 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); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } interface ERC223Interface { function balanceOf(address who) constant returns (uint); function transfer(address to, uint value) returns (bool); function transfer(address to, uint value, bytes data) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } interface ERC223ReceivingContract { /// @dev Function that is called when a user or another contract wants to transfer funds. /// @param _from Transaction initiator, analogue of msg.sender /// @param _value Number of tokens to transfer. /// @param _data Data containing a function signature and/or parameters function tokenFallback(address _from, uint256 _value, bytes _data) public; } interface NativeAssetInterface { // PUBLIC METHODS function deposit() public payable; function withdraw(uint wad) public; } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (string); function getSymbol() view returns (string); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } interface ExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } interface PriceFeedInterface { // EVENTS event PriceUpdated(uint timestamp); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices); // PUBLIC VIEW METHODS // Get asset specific information function getName(address ofAsset) view returns (string); function getSymbol(address ofAsset) view returns (string); function getDecimals(address ofAsset) view returns (uint); // Get price feed operation specific information function getQuoteAsset() view returns (address); function getInterval() view returns (uint); function getValidity() view returns (uint); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function hasRecentPrice(address ofAsset) view returns (bool isRecent); function hasRecentPrices(address[] ofAssets) view returns (bool areRecent); function getPrice(address ofAsset) view returns (bool isRecent, uint price, uint decimal); function getPrices(address[] ofAssets) view returns (bool areRecent, uint[] prices, uint[] decimals); function getInvertedPrice(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint decimal); function getReferencePrice(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal); function getOrderPrice( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice); function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent); } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( string ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS // Constant fields bytes32 public constant TERMS_AND_CONDITIONS = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; // Hashed terms and conditions as displayed on IPFS. // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public NATIVE_ASSET; // Address of wrapped native asset contract address public GOVERNANCE; // Address of Melon protocol governance contract // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofNativeAsset Address of wrapped native asset contract function Version( string versionNumber, address ofGovernance, address ofNativeAsset ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; NATIVE_ASSET = ofNativeAsset; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofExchangeAdapters Addresses of exchange adapters /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( string ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); // Either novel fund name or previous owner of fund name require(managerToFunds[msg.sender] == 0); // Add limitation for simpler migration process of shutting down and setting up fund address ofFund = new Fund( msg.sender, ofFundName, ofQuoteAsset, ofManagementFee, ofPerformanceFee, NATIVE_ASSET, ofCompliance, ofRiskMgmt, ofPriceFeed, ofExchanges, ofExchangeAdapters ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; FundUpdated(ofFund); } /// @dev Dereference Fund and trigger selfdestruct /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract Asset is DSMath, AssetInterface, ERC223Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); // if (codeLength > 0) { // ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); // receiver.tokenFallback(msg.sender, _value, empty); // } Transfer(msg.sender, _to, _value, empty); return true; } /** * @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract * @dev Function that is called when a user or contract wants to transfer funds * @param _to Address of token receiver * @param _value Number of tokens to transfer * @param _data Data to be sent to tokenFallback * @return Returns success of function call */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); // if (codeLength > 0) { // ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); // receiver.tokenFallback(msg.sender, _value, _data); // } Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != 0x0); require(_to != 0x0); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != 0x0); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 // require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } } contract Shares is Asset, SharesInterface { // FIELDS // Constructor fields string public name; string public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(string _name, string _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS // PUBLIC VIEW METHODS function getName() view returns (string) { return name; } function getSymbol() view returns (string) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } function transfer(address _to, uint256 _value) public returns (bool) { require(_to == address(this)); } function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to == address(this)); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to == address(this)); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { totalSupply = add(totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); Created(msg.sender, now, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { totalSupply = sub(totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); Annihilated(msg.sender, now, shareQuantity); } } contract RestrictedShares is Shares { // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function RestrictedShares( string _name, string _symbol, uint _decimal, uint _creationTime ) Shares(_name, _symbol, _decimal, _creationTime) {} // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(msg.sender == address(this) || _to == address(this)); uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value, empty); return true; } /** * @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract * @dev Function that is called when a user or contract wants to transfer funds * @param _to Address of token receiver * @param _value Number of tokens to transfer * @param _data Data to be sent to tokenFallback * @return Returns success of function call */ function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(msg.sender == address(this) || _to == address(this)); uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(msg.sender == address(this)); require(_spender != 0x0); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract Fund is DSMath, DBC, Owned, RestrictedShares, FundInterface, ERC223ReceivingContract { // TYPES struct Modules { // Describes all modular parts, standardised through an interface PriceFeedInterface pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum RequestStatus { active, cancelled, executed } enum RequestType { invest, redeem, tokenFallbackRedeem } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request RequestType requestType; // Enum: invest, redeem, tokenFallbackRedeem address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } enum OrderStatus { active, partiallyFilled, fullyFilled, cancelled } enum OrderType { make, take } struct Order { // Describes and logs whenever assets enter and leave fund due to Manager uint exchangeId; // Id as returned from exchange OrderStatus status; // Enum: active, partiallyFilled, fullyFilled, cancelled OrderType orderType; // Enum: make, take address sellAsset; // Asset (as registered in Asset registrar) to be sold address buyAsset; // Asset (as registered in Asset registrar) to be bought uint sellQuantity; // Quantity of sellAsset to be sold uint buyQuantity; // Quantity of sellAsset to be bought uint timestamp; // Time of order creation in seconds uint fillQuantity; // Buy quantity filled; Always less than buy_quantity } struct Exchange { address exchange; // Address of the exchange ExchangeInterface exchangeAdapter; //Exchange adapter contracts respective to the exchange bool isApproveOnly; // True in case of exchange implementation which requires are approved when an order is made instead of transfer } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 4; // Max ownable assets by the fund supported by gas limits // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract NativeAssetInterface public NATIVE_ASSET; // Native asset as ERC20 contract // Methods fields Modules public module; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants bool public isInvestAllowed; // User option, if false fund rejects Melon investments bool public isRedeemAllowed; // User option, if false fund rejects Melon redemptions; Redemptions using slices always possible Order[] public orders; // All the orders this fund placed on exchanges mapping (uint => mapping(address => uint)) public exchangeIdsToOpenMakeOrderIds; // exchangeIndex to: asset to open make order ID ; if no open make orders, orderID is zero address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest/redeem using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofExchangeAdapters Addresses of exchange adapters /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, string withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofNativeAsset, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofExchangeAdapters ) RestrictedShares(withName, "MLNF", 18, now) { isInvestAllowed = true; isRedeemAllowed = true; owner = ofManager; require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; module.compliance = ComplianceInterface(ofCompliance); module.riskmgmt = RiskMgmtInterface(ofRiskMgmt); module.pricefeed = PriceFeedInterface(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { ExchangeInterface adapter = ExchangeInterface(ofExchangeAdapters[i]); bool isApproveOnly = adapter.isApproveOnly(); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: adapter, isApproveOnly: isApproveOnly })); } // Require Quote assets exists in pricefeed QUOTE_ASSET = Asset(ofQuoteAsset); NATIVE_ASSET = NativeAssetInterface(ofNativeAsset); // Quote Asset and Native asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; ownedAssets.push(ofNativeAsset); isInAssetList[ofNativeAsset] = true; require(address(QUOTE_ASSET) == module.pricefeed.getQuoteAsset()); // Sanity check atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION function enableInvestment() external pre_cond(isOwner()) { isInvestAllowed = true; } function disableInvestment() external pre_cond(isOwner()) { isInvestAllowed = false; } function enableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = true; } function disableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = false; } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received function requestInvestment( uint giveQuantity, uint shareQuantity, bool isNativeAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed) // investment using Melon has not been deactivated by the Manager pre_cond(module.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestType: RequestType.invest, requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET), shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } /// @notice Give shares of this fund to receive melon tokens /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity function requestRedemption( uint shareQuantity, uint receiveQuantity, bool isNativeAsset ) external pre_cond(!isShutDown) pre_cond(isRedeemAllowed) // Redemption using Melon has not been deactivated by Manager pre_cond(module.compliance.isRedemptionPermitted(msg.sender, shareQuantity, receiveQuantity)) // Compliance Module: Redemption permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestType: RequestType.redeem, requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET), shareQuantity: shareQuantity, giveQuantity: shareQuantity, receiveQuantity: receiveQuantity, timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond(requests[id].requestType != RequestType.redeem || requests[id].shareQuantity <= balances[requests[id].participant]) // request owner does not own enough shares pre_cond( totalSupply == 0 || ( now >= add(requests[id].timestamp, module.pricefeed.getInterval()) && module.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; // PriceFeed Module: No recent updates for fund asset list require(module.pricefeed.hasRecentPrice(address(request.requestAsset))); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset == address(NATIVE_ASSET)) { var (isPriceRecent, invertedNativeAssetPrice, nativeAssetDecimal) = module.pricefeed.getInvertedPrice(address(NATIVE_ASSET)); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedNativeAssetPrice) / 10 ** nativeAssetDecimal; } if ( isInvestAllowed && request.requestType == RequestType.invest && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transferFrom(request.participant, this, costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting } else if ( isRedeemAllowed && request.requestType == RequestType.redeem && request.receiveQuantity <= costQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value annihilateShares(request.participant, request.shareQuantity); // Accounting } else if ( isRedeemAllowed && request.requestType == RequestType.tokenFallbackRedeem && request.receiveQuantity <= costQuantity ) { request.status = RequestStatus.executed; assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value annihilateShares(this, request.shareQuantity); // Accounting } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Makes an order on the selected exchange /// @dev These are orders that are not expected to settle immediately. Sufficient balance (== sellQuantity) of sellAsset /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought function makeOrder( uint exchangeNumber, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external pre_cond(isOwner()) pre_cond(!isShutDown) { require(buyAsset != address(this)); // Prevent buying of own fund token require(quantityHeldInCustodyOfExchange(sellAsset) == 0); // Curr only one make order per sellAsset allowed. Please wait or cancel existing make order. require(module.pricefeed.existsPriceOnAssetPair(sellAsset, buyAsset)); // PriceFeed module: Requested asset pair not valid var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(sellAsset, buyAsset); require(isRecent); // Reference price is required to be recent require( module.riskmgmt.isMakePermitted( module.pricefeed.getOrderPrice( sellAsset, buyAsset, sellQuantity, buyQuantity ), referencePrice, sellAsset, buyAsset, sellQuantity, buyQuantity ) ); // RiskMgmt module: Make order not permitted require(isInAssetList[buyAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached require(AssetInterface(sellAsset).approve(exchanges[exchangeNumber].exchange, sellQuantity)); // Approve exchange to spend assets // Since there is only one openMakeOrder allowed for each asset, we can assume that openMakeOrderId is set as zero by quantityHeldInCustodyOfExchange() function require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("makeOrder(address,address,address,uint256,uint256)")), exchanges[exchangeNumber].exchange, sellAsset, buyAsset, sellQuantity, buyQuantity)); exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] = exchanges[exchangeNumber].exchangeAdapter.getLastOrderId(exchanges[exchangeNumber].exchange); // Success defined as non-zero order id require(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] != 0); // Update ownedAssets array and isInAssetList, isInOpenMakeOrder mapping isInOpenMakeOrder[buyAsset] = true; if (!isInAssetList[buyAsset]) { ownedAssets.push(buyAsset); isInAssetList[buyAsset] = true; } orders.push(Order({ exchangeId: exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset], status: OrderStatus.active, orderType: OrderType.make, sellAsset: sellAsset, buyAsset: buyAsset, sellQuantity: sellQuantity, buyQuantity: buyQuantity, timestamp: now, fillQuantity: 0 })); OrderUpdated(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset]); } /// @notice Takes an active order on the selected exchange /// @dev These are orders that are expected to settle immediately /// @param id Active order id /// @param receiveQuantity Buy quantity of what others are selling on selected Exchange function takeOrder(uint exchangeNumber, uint id, uint receiveQuantity) external pre_cond(isOwner()) pre_cond(!isShutDown) { // Get information of order by order id Order memory order; // Inverse variable terminology! Buying what another person is selling ( order.sellAsset, order.buyAsset, order.sellQuantity, order.buyQuantity ) = exchanges[exchangeNumber].exchangeAdapter.getOrder(exchanges[exchangeNumber].exchange, id); // Check pre conditions require(order.sellAsset != address(this)); // Prevent buying of own fund token require(module.pricefeed.existsPriceOnAssetPair(order.buyAsset, order.sellAsset)); // PriceFeed module: Requested asset pair not valid require(isInAssetList[order.sellAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(order.buyAsset, order.sellAsset); require(isRecent); // Reference price is required to be recent require(receiveQuantity <= order.sellQuantity); // Not enough quantity of order for what is trying to be bought uint spendQuantity = mul(receiveQuantity, order.buyQuantity) / order.sellQuantity; require(AssetInterface(order.buyAsset).approve(exchanges[exchangeNumber].exchange, spendQuantity)); // Could not approve spending of spendQuantity of order.buyAsset require( module.riskmgmt.isTakePermitted( module.pricefeed.getOrderPrice( order.buyAsset, order.sellAsset, order.buyQuantity, // spendQuantity order.sellQuantity // receiveQuantity ), referencePrice, order.buyAsset, order.sellAsset, order.buyQuantity, order.sellQuantity )); // RiskMgmt module: Take order not permitted // Execute request require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("takeOrder(address,uint256,uint256)")), exchanges[exchangeNumber].exchange, id, receiveQuantity)); // Update ownedAssets array and isInAssetList mapping if (!isInAssetList[order.sellAsset]) { ownedAssets.push(order.sellAsset); isInAssetList[order.sellAsset] = true; } order.exchangeId = id; order.status = OrderStatus.fullyFilled; order.orderType = OrderType.take; order.timestamp = now; order.fillQuantity = receiveQuantity; orders.push(order); OrderUpdated(id); } /// @notice Cancels orders that were not expected to settle immediately, i.e. makeOrders /// @dev Reduce exposure with exchange interaction /// @param id Active order id of this order array with order owner of this contract on selected Exchange function cancelOrder(uint exchangeNumber, uint id) external pre_cond(isOwner() || isShutDown) { // Get information of fund order by order id Order order = orders[id]; // Execute request require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("cancelOrder(address,uint256)")), exchanges[exchangeNumber].exchange, order.exchangeId)); order.status = OrderStatus.cancelled; OrderUpdated(id); } // PUBLIC METHODS // PUBLIC METHODS : ERC223 /// @dev Standard ERC223 function that handles incoming token transfers. /// @dev This type of redemption can be seen as a "market order", where price is calculated at execution time /// @param ofSender Token sender address. /// @param tokenAmount Amount of tokens sent. /// @param metadata Transaction metadata. function tokenFallback( address ofSender, uint tokenAmount, bytes metadata ) { if (msg.sender != address(this)) { // when ofSender is a recognized exchange, receive tokens, otherwise revert for (uint i; i < exchanges.length; i++) { if (exchanges[i].exchange == ofSender) return; // receive tokens and do nothing } revert(); } else { // otherwise, make a redemption request requests.push(Request({ participant: ofSender, status: RequestStatus.active, requestType: RequestType.tokenFallbackRedeem, requestAsset: address(QUOTE_ASSET), // redeem in QUOTE_ASSET shareQuantity: tokenAmount, giveQuantity: tokenAmount, // shares being sent receiveQuantity: 0, // value of the shares at request time timestamp: now, atUpdateId: module.pricefeed.getLastUpdateId() })); RequestUpdated(getLastRequestId()); } } // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPrice(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal address[] memory tempOwnedAssets; // To store ownedAssets tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(this)), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = module.pricefeed.getPrice(ofAsset); if (!isRecent) { revert(); } // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || ofAsset == address(NATIVE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } PortfolioContent(assetHoldings, assetPrice, assetDecimals); } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(totalSupply, feesShareQuantity); sharePrice = nav > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: totalSupply, timestamp: now }); FeesConverted(now, feesShareQuantity, unclaimedFees); CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(this)), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(this)) < ownershipQuantities[i]) { isShutDown = true; ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint j = 0; j < requestedAssets.length; ++j) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[j]; if (ownershipQuantities[j] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[j])) { revert(); } } Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangeIdsToOpenMakeOrderIds[i][ofAsset] == 0) { continue; } var (sellAsset, , sellQuantity, ) = exchanges[i].exchangeAdapter.getOrder(exchanges[i].exchange, exchangeIdsToOpenMakeOrderIds[i][ofAsset]); if (sellQuantity == 0) { exchangeIdsToOpenMakeOrderIds[i][ofAsset] = 0; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (exchanges[i].isApproveOnly) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(module.pricefeed), address(module.compliance), address(module.riskmgmt) ); } function getLastOrderId() view returns (uint) { return orders.length - 1; } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getNameHash() view returns (bytes32) { return bytes32(keccak256(name)); } function getManager() view returns (address) { return owner; } } contract WETH9_ { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } }
User option, if false fund rejects Melon investments
bool public isInvestAllowed;
12,885,067
[ 1, 1299, 1456, 16, 309, 629, 284, 1074, 4925, 87, 490, 292, 265, 2198, 395, 1346, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 353, 3605, 395, 5042, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0xC4CE98E765BF68f7138DEb3c69c976612E48C885/sources/Token.sol
Initializes contract with initial supply tokens to the creator of the contract */
constructor () public payable{ balanceOf[address(this)] = totalSupply; companyAddress.transfer(fee); }
5,155,383
[ 1, 9685, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 8843, 429, 95, 203, 3639, 11013, 951, 63, 2867, 12, 2211, 25887, 273, 2078, 3088, 1283, 31, 203, 3639, 9395, 1887, 18, 13866, 12, 21386, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/SafeMath96.sol 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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint96 a, uint256 b) internal pure returns (uint96) { require(uint256(uint96(b)) == b, "SafeMath: addition overflow"); uint96 c = a + uint96(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(uint96 a, uint256 b) internal pure returns (uint96) { require(uint256(uint96(b)) == b, "SafeMath: subtraction overflow"); return sub(a, uint96(b), "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/spec_interfaces/ICommittee.sol pragma solidity 0.6.12; /// @title Committee contract interface interface ICommittee { event CommitteeChange(address indexed addr, uint256 weight, bool certification, bool inCommittee); event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification); // No external functions /* * External functions */ /// Notifies a weight change of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param weight is the updated weight of the committee member function memberWeightChange(address addr, uint256 weight) external /* onlyElectionsContract onlyWhenActive */; /// Notifies a change in the certification of a member /// @dev Called only by: Elections contract /// @param addr is the committee member address /// @param isCertified is the updated certification state of the member function memberCertificationChange(address addr, bool isCertified) external /* onlyElectionsContract onlyWhenActive */; /// Notifies a member removal for example due to voteOut or voteUnready /// @dev Called only by: Elections contract /// @param memberRemoved is the removed committee member address /// @return memberRemoved indicates whether the member was removed from the committee /// @return removedMemberWeight indicates the removed member weight /// @return removedMemberCertified indicates whether the member was in the certified committee function removeMember(address addr) external returns (bool memberRemoved, uint removedMemberWeight, bool removedMemberCertified)/* onlyElectionContract */; /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) /// The new member will be added only if it is qualified to join the committee /// @dev Called only by: Elections contract /// @param addr is the added committee member address /// @param weight is the added member weight /// @param isCertified is the added member certification state /// @return memberAdded bool indicates whether the member was added function addMember(address addr, uint256 weight, bool isCertified) external returns (bool memberAdded) /* onlyElectionsContract */; /// Checks if addMember() would add a the member to the committee (qualified to join) /// @param addr is the candidate committee member address /// @param weight is the candidate committee member weight /// @return wouldAddMember bool indicates whether the member will be added function checkAddMember(address addr, uint256 weight) external view returns (bool wouldAddMember); /// Returns the committee members and their weights /// @return addrs is the committee members list /// @return weights is an array of uint, indicating committee members list weight /// @return certification is an array of bool, indicating the committee members certification status function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification); /// Returns the currently appointed committee data /// @return generalCommitteeSize is the number of members in the committee /// @return certifiedCommitteeSize is the number of certified members in the committee /// @return totalWeight is the total effective stake (weight) of the committee function getCommitteeStats() external view returns (uint generalCommitteeSize, uint certifiedCommitteeSize, uint totalWeight); /// Returns a committee member data /// @param addr is the committee member address /// @return inCommittee indicates whether the queried address is a member in the committee /// @return weight is the committee member weight /// @return isCertified indicates whether the committee member is certified /// @return totalCommitteeWeight is the total weight of the committee. function getMemberInfo(address addr) external view returns (bool inCommittee, uint weight, bool isCertified, uint totalCommitteeWeight); /// Emits a CommitteeSnapshot events with current committee info /// @dev a CommitteeSnapshot is useful on contract migration or to remove the need to track past events. function emitCommitteeSnapshot() external; /* * Governance functions */ event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue); /// Sets the maximum number of committee members /// @dev governance function called only by the functional manager /// @dev when reducing the number of members, the bottom ones are removed from the committee /// @param _maxCommitteeSize is the maximum number of committee members function setMaxCommitteeSize(uint8 _maxCommitteeSize) external /* onlyFunctionalManager */; /// Returns the maximum number of committee members /// @return maxCommitteeSize is the maximum number of committee members function getMaxCommitteeSize() external view returns (uint8); /// Imports the committee members from a previous committee contract during migration /// @dev initialization function called only by the initializationManager /// @dev does not update the reward contract to avoid incorrect notifications /// @param previousCommitteeContract is the address of the previous committee contract function importMembers(ICommittee previousCommitteeContract) external /* onlyInitializationAdmin */; } // File: contracts/spec_interfaces/IProtocolWallet.sol pragma solidity 0.6.12; /// @title Protocol Wallet interface interface IProtocolWallet { event FundsAddedToPool(uint256 added, uint256 total); /* * External functions */ /// Returns the address of the underlying staked token /// @return balance is the wallet balance function getBalance() external view returns (uint256 balance); /// Transfers the given amount of orbs tokens form the sender to this contract and updates the pool /// @dev assumes the caller approved the amount prior to calling /// @param amount is the amount to add to the wallet function topUp(uint256 amount) external; /// Withdraws from pool to the client address, limited by the pool's MaxRate. /// @dev may only be called by the wallet client /// @dev no more than MaxRate x time period since the last withdraw may be withdrawn /// @dev allocation that wasn't withdrawn can not be withdrawn in the next call /// @param amount is the amount to withdraw function withdraw(uint256 amount) external; /* onlyClient */ /* * Governance functions */ event ClientSet(address client); event MaxAnnualRateSet(uint256 maxAnnualRate); event EmergencyWithdrawal(address addr, address token); event OutstandingTokensReset(uint256 startTime); /// Sets a new annual withdraw rate for the pool /// @dev governance function called only by the migration owner /// @dev the rate for a duration is duration x annualRate / 1 year /// @param _annualRate is the maximum annual rate that can be withdrawn function setMaxAnnualRate(uint256 _annualRate) external; /* onlyMigrationOwner */ /// Returns the annual withdraw rate of the pool /// @return annualRate is the maximum annual rate that can be withdrawn function getMaxAnnualRate() external view returns (uint256); /// Resets the outstanding tokens to new start time /// @dev governance function called only by the migration owner /// @dev the next duration will be calculated starting from the given time /// @param startTime is the time to set as the last withdrawal time function resetOutstandingTokens(uint256 startTime) external; /* onlyMigrationOwner */ /// Emergency withdraw the wallet funds /// @dev governance function called only by the migration owner /// @dev used in emergencies, when a migration to a new wallet is needed /// @param erc20 is the erc20 address of the token to withdraw function emergencyWithdraw(address erc20) external; /* onlyMigrationOwner */ /// Sets the address of the client that can withdraw funds /// @dev governance function called only by the functional owner /// @param _client is the address of the new client function setClient(address _client) external; /* onlyFunctionalOwner */ } // File: contracts/spec_interfaces/IStakingRewards.sol pragma solidity 0.6.12; /// @title Staking rewards contract interface interface IStakingRewards { event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta); event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 stakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta); event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards); event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight); event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille); /* * External functions */ /// Returns the current reward balance of the given address. /// @dev calculates the up to date balances (differ from the state) /// @param addr is the address to query /// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role /// @return guardianStakingRewardsBalance the rewards awarded to the guardian role function getStakingRewardsBalance(address addr) external view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance); /// Claims the staking rewards balance of an addr, staking the rewards /// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface /// @dev includes the rewards for both the delegator and guardian roles /// @dev calculates the up to date rewards prior to distribute them to the staking contract /// @param addr is the address to claim rewards for function claimStakingRewards(address addr) external; /// Returns the current global staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero /// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet function getStakingRewardsState() external view returns ( uint96 stakingRewardsPerWeight, uint96 unclaimedStakingRewards ); /// Returns the current guardian staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards /// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator /// @param guardian is the guardian to query /// @return balance is the staking rewards balance for the guardian role /// @return claimed is the staking rewards for the guardian role that were claimed /// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero /// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update /// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation /// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update function getGuardianStakingRewardsData(address guardian) external view returns ( uint256 balance, uint256 claimed, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 lastStakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta ); /// Returns the current delegator staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @param delegator is the delegator to query /// @return balance is the staking rewards balance for the delegator role /// @return claimed is the staking rewards for the delegator role that were claimed /// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards /// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation /// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update function getDelegatorStakingRewardsData(address delegator) external view returns ( uint256 balance, uint256 claimed, address guardian, uint256 lastDelegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta ); /// Returns an estimation for the delegator and guardian staking rewards for a given duration /// @dev the returned value is an estimation, assuming no change in the PoS state /// @dev the period calculated for start from the current block time until the current time + duration. /// @param addr is the address to estimate rewards for /// @param duration is the duration to calculate for in seconds /// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role /// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role function estimateFutureRewards(address addr, uint256 duration) external view returns ( uint256 estimatedDelegatorStakingRewards, uint256 estimatedGuardianStakingRewards ); /// Sets the guardian's delegators staking reward portion /// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille /// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille) function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external; /// Returns a guardian's delegators staking reward portion /// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille /// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille); /// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards /// @dev The staking wallet balance must always larger than the allocated value /// @return allocated is the amount of tokens allocated in the staking rewards wallet function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated); /// Returns the current annual staking reward rate /// @dev calculated based on the current total committee weight /// @return annualRate is the current staking reward rate in percent-mille function getCurrentStakingRewardsRatePercentMille() external view returns (uint256 annualRate); /// Notifies an expected change in the committee membership of the guardian /// @dev Called only by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @dev triggers update of the global rewards state and the guardian rewards state /// @dev updates the rewards state based on the committee state prior to the change /// @param guardian is the guardian who's committee membership is updated /// @param weight is the weight of the guardian prior to the change /// @param totalCommitteeWeight is the total committee weight prior to the change /// @param inCommittee indicates whether the guardian was in the committee prior to the change /// @param inCommitteeAfter indicates whether the guardian is in the committee after the change function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */; /// Notifies an expected change in a delegator and his guardian delegation state /// @dev Called only by: the Delegation contract /// @dev called upon expected change in a delegator's delegation state /// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state /// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly /// @param guardian is the delegator's guardian prior to the change /// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change /// @param delegator is the delegator about to change delegation state /// @param delegatorStake is the stake of the delegator /// @param nextGuardian is the delegator's guardian after to the change /// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */; /* * Governance functions */ event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap); event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille); event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract); event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards); event EmergencyWithdrawal(address addr, address token); /// Activates staking rewards allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set to the previous contract deactivation time /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */; /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external /* onlyMigrationManager */; /// Sets the default delegators staking reward portion /// @dev governance function called only by the functional manager /// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille) function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */; /// Returns the default delegators staking reward portion /// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32); /// Sets the maximum delegators staking reward portion /// @dev governance function called only by the functional manager /// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000) function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager */; /// Returns the default delegators staking reward portion /// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32); /// Sets the annual rate and cap for the staking reward /// @dev governance function called only by the functional manager /// @param annualRateInPercentMille is the annual rate in percent-mille /// @param annualCap is the annual staking rewards cap function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external /* onlyFunctionalManager */; /// Returns the annual staking reward rate /// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille function getAnnualStakingRewardsRatePercentMille() external view returns (uint32); /// Returns the annual staking rewards cap /// @return annualStakingRewardsCap is the annual rate in percent-mille function getAnnualStakingRewardsCap() external view returns (uint256); /// Checks if rewards allocation is active /// @return rewardAllocationActive is a bool that indicates that rewards allocation is active function isRewardAllocationActive() external view returns (bool); /// Returns the contract's settings /// @return annualStakingRewardsCap is the annual rate in percent-mille /// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille /// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille /// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille /// @return rewardAllocationActive is a bool that indicates that rewards allocation is active function getSettings() external view returns ( uint annualStakingRewardsCap, uint32 annualStakingRewardsRatePercentMille, uint32 defaultDelegatorsStakingRewardsPercentMille, uint32 maxDelegatorsStakingRewardsPercentMille, bool rewardAllocationActive ); /// Migrates the staking rewards balance of the given addresses to a new staking rewards contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param addrs is the list of addresses to migrate function migrateRewardsBalance(address[] calldata addrs) external; /// Accepts addresses balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param addrs is the list migrated addresses /// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address /// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address /// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists. function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external; /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external /* onlyMigrationManager */; } // File: contracts/spec_interfaces/IDelegations.sol pragma solidity 0.6.12; /// @title Delegations contract interface interface IDelegations /* is IStakeChangeNotifier */ { // Delegation state change events event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address indexed delegator, uint256 delegatorContributedStake); // Function calls event Delegated(address indexed from, address indexed to); /* * External functions */ /// Delegate your stake /// @dev updates the election contract on the changes in the delegated stake /// @dev updates the rewards contract on the upcoming change in the delegator's delegation state /// @param to is the address to delegate to function delegate(address to) external /* onlyWhenActive */; /// Refresh the address stake for delegation power based on the staking contract /// @dev Disabled stake change update notifications from the staking contract may create mismatches /// @dev refreshStake re-syncs the stake data with the staking contract /// @param addr is the address to refresh its stake function refreshStake(address addr) external /* onlyWhenActive */; /// Refresh the addresses stake for delegation power based on the staking contract /// @dev Batched version of refreshStake /// @dev Disabled stake change update notifications from the staking contract may create mismatches /// @dev refreshStakeBatch re-syncs the stake data with the staking contract /// @param addrs is the list of addresses to refresh their stake function refreshStakeBatch(address[] calldata addrs) external /* onlyWhenActive */; /// Returns the delegate address of the given address /// @param addr is the address to query /// @return delegation is the address the addr delegated to function getDelegation(address addr) external view returns (address); /// Returns a delegator info /// @param addr is the address to query /// @return delegation is the address the addr delegated to /// @return delegatorStake is the stake of the delegator as reflected in the delegation contract function getDelegationInfo(address addr) external view returns (address delegation, uint256 delegatorStake); /// Returns the delegated stake of an addr /// @dev an address that is not self delegating has a 0 delegated stake /// @param addr is the address to query /// @return delegatedStake is the address delegated stake function getDelegatedStake(address addr) external view returns (uint256); /// Returns the total delegated stake /// @dev delegatedStake - the total stake delegated to an address that is self delegating /// @dev the delegated stake of a non self-delegated address is 0 /// @return totalDelegatedStake is the total delegatedStake of all the addresses function getTotalDelegatedStake() external view returns (uint256) ; /* * Governance functions */ event DelegationsImported(address[] from, address indexed to); event DelegationInitialized(address indexed from, address indexed to); /// Imports delegations during initial migration /// @dev initialization function called only by the initializationManager /// @dev Does not update the Rewards or Election contracts /// @dev assumes deactivated Rewards /// @param from is a list of delegator addresses /// @param to is the address the delegators delegate to function importDelegations(address[] calldata from, address to) external /* onlyMigrationManager onlyDuringDelegationImport */; /// Initializes the delegation of an address during initial migration /// @dev initialization function called only by the initializationManager /// @dev behaves identically to a delegate transaction sent by the delegator /// @param from is the delegator addresses /// @param to is the delegator delegates to function initDelegation(address from, address to) external /* onlyInitializationAdmin */; } // File: contracts/IMigratableStakingContract.sol pragma solidity 0.6.12; /// @title An interface for staking contracts which support stake migration. interface IMigratableStakingContract { /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The number of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external; event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/IStakingContract.sol pragma solidity 0.6.12; /// @title An interface for staking contracts. interface IStakingContract { /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external; /// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external; /// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external; /// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender. function restake() external; /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to properly batch/paginate their requests. /// @param _totalAmount uint256 The total amount of rewards to distribute. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external; /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The total stake. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256); /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256); /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime); /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/spec_interfaces/IManagedContract.sol pragma solidity 0.6.12; /// @title managed contract interface, used by the contracts registry to notify the contract on updates interface IManagedContract /* is ILockable, IContractRegistryAccessor, Initializable */ { /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external; } // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.6.12; /// @title Contract registry contract interface /// @dev The contract registry holds Orbs PoS contracts and managers lists /// @dev The contract registry updates the managed contracts on changes in the contract list /// @dev Governance functions restricted to managers access the registry to retrieve the manager address /// @dev The contract registry represents the source of truth for Orbs Ethereum contracts /// @dev By tracking the registry events or query before interaction, one can access the up to date contracts interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// Updates the contracts address and emits a corresponding event /// @dev governance function called only by the migrationManager or registryAdmin /// @param contractName is the contract name, used to identify it /// @param addr is the contract updated address /// @param managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdminOrMigrationManager */; /// Returns the current address of the given contracts /// @param contractName is the contract name, used to identify it /// @return addr is the contract updated address function getContract(string calldata contractName) external view returns (address); /// Returns the list of contract addresses managed by the registry /// @dev Managed contracts are updated on changes in the registry contracts addresses /// @return addrs is the list of managed contracts function getManagedContracts() external view returns (address[] memory); /// Locks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin /// @dev When set all onlyWhenActive functions will revert function lockContracts() external /* onlyAdminOrMigrationManager */; /// Unlocks all the managed contracts /// @dev governance function called only by the migrationManager or registryAdmin function unlockContracts() external /* onlyAdminOrMigrationManager */; /// Updates a manager address and emits a corresponding event /// @dev governance function called only by the registryAdmin /// @dev the managers list is a flexible list of role to the manager's address /// @param role is the managers' role name, for example "functionalManager" /// @param manager is the manager updated address function setManager(string calldata role, address manager) external /* onlyAdmin */; /// Returns the current address of the given manager /// @param role is the manager name, used to identify it /// @return addr is the manager updated address function getManager(string calldata role) external view returns (address); /// Sets a new contract registry to migrate to /// @dev governance function called only by the registryAdmin /// @dev updates the registry address record in all the managed contracts /// @dev by tracking the emitted ContractRegistryUpdated, tools can track the up to date contracts /// @param newRegistry is the new registry contract function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the previous contract registry address /// @dev used when the setting the contract as a new registry to assure a valid registry /// @return previousContractRegistry is the previous contract registry function getPreviousContractRegistry() external view returns (address); } // File: contracts/spec_interfaces/IContractRegistryAccessor.sol pragma solidity 0.6.12; interface IContractRegistryAccessor { /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newRegistry is the new registry contract function setContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; /// Returns the contract registry address /// @return contractRegistry is the contract registry address function getContractRegistry() external view returns (IContractRegistry contractRegistry); function setRegistryAdmin(address _registryAdmin) external /* onlyInitializationAdmin */; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/WithClaimableRegistryManagement.sol pragma solidity 0.6.12; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() external onlyPendingRegistryAdmin { _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } // File: contracts/Initializable.sol pragma solidity 0.6.12; contract Initializable { address private _initializationAdmin; event InitializationComplete(); /// Constructor /// Sets the initializationAdmin to the contract deployer /// The initialization admin may call any manager only function until initializationComplete constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ /// Returns the initializationAdmin address function initializationAdmin() public view returns (address) { return _initializationAdmin; } /// Finalizes the initialization and revokes the initializationAdmin role function initializationComplete() external onlyInitializationAdmin { _initializationAdmin = address(0); emit InitializationComplete(); } /// Checks if the initialization was completed function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.6.12; contract ContractRegistryAccessor is IContractRegistryAccessor, WithClaimableRegistryManagement, Initializable { IContractRegistry private contractRegistry; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) public { require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0"); setContractRegistry(_contractRegistry); _transferRegistryManagement(_registryAdmin); } modifier onlyAdmin { require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)"); _; } modifier onlyMigrationManager { require(isMigrationManager(), "sender is not the migration manager"); _; } modifier onlyFunctionalManager { require(isFunctionalManager(), "sender is not the functional manager"); _; } /// Checks whether the caller is Admin: either the contract registry, the registry admin, or the initialization admin function isAdmin() internal view returns (bool) { return msg.sender == address(contractRegistry) || msg.sender == registryAdmin() || msg.sender == initializationAdmin(); } /// Checks whether the caller is a specific manager role or and Admin /// @dev queries the registry contract for the up to date manager assignment function isManager(string memory role) internal view returns (bool) { IContractRegistry _contractRegistry = contractRegistry; return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender; } /// Checks whether the caller is the migration manager function isMigrationManager() internal view returns (bool) { return isManager('migrationManager'); } /// Checks whether the caller is the functional manager function isFunctionalManager() internal view returns (bool) { return isManager('functionalManager'); } /* * Contract getters, return the address of a contract by calling the contract registry */ function getProtocolContract() internal view returns (address) { return contractRegistry.getContract("protocol"); } function getStakingRewardsContract() internal view returns (address) { return contractRegistry.getContract("stakingRewards"); } function getFeesAndBootstrapRewardsContract() internal view returns (address) { return contractRegistry.getContract("feesAndBootstrapRewards"); } function getCommitteeContract() internal view returns (address) { return contractRegistry.getContract("committee"); } function getElectionsContract() internal view returns (address) { return contractRegistry.getContract("elections"); } function getDelegationsContract() internal view returns (address) { return contractRegistry.getContract("delegations"); } function getGuardiansRegistrationContract() internal view returns (address) { return contractRegistry.getContract("guardiansRegistration"); } function getCertificationContract() internal view returns (address) { return contractRegistry.getContract("certification"); } function getStakingContract() internal view returns (address) { return contractRegistry.getContract("staking"); } function getSubscriptionsContract() internal view returns (address) { return contractRegistry.getContract("subscriptions"); } function getStakingRewardsWallet() internal view returns (address) { return contractRegistry.getContract("stakingRewardsWallet"); } function getBootstrapRewardsWallet() internal view returns (address) { return contractRegistry.getContract("bootstrapRewardsWallet"); } function getGeneralFeesWallet() internal view returns (address) { return contractRegistry.getContract("generalFeesWallet"); } function getCertifiedFeesWallet() internal view returns (address) { return contractRegistry.getContract("certifiedFeesWallet"); } function getStakingContractHandler() internal view returns (address) { return contractRegistry.getContract("stakingContractHandler"); } /* * Governance functions */ event ContractRegistryAddressUpdated(address addr); /// Sets the contract registry address /// @dev governance function called only by an admin /// @param newContractRegistry is the new registry contract function setContractRegistry(IContractRegistry newContractRegistry) public override onlyAdmin { require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry"); contractRegistry = newContractRegistry; emit ContractRegistryAddressUpdated(address(newContractRegistry)); } /// Returns the contract registry that the contract is set to use /// @return contractRegistry is the registry contract address function getContractRegistry() public override view returns (IContractRegistry) { return contractRegistry; } function setRegistryAdmin(address _registryAdmin) external override onlyInitializationAdmin { _transferRegistryManagement(_registryAdmin); } } // File: contracts/spec_interfaces/ILockable.sol pragma solidity 0.6.12; /// @title lockable contract interface, allows to lock a contract interface ILockable { event Locked(); event Unlocked(); /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external /* onlyMigrationManager */; /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external /* onlyMigrationManager */; /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() view external returns (bool); } // File: contracts/Lockable.sol pragma solidity 0.6.12; /// @title lockable contract contract Lockable is ILockable, ContractRegistryAccessor { bool public locked; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {} /// Locks the contract to external non-governance function calls /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon locking all managed contracts /// @dev getters and migration functions remain active also for locked contracts /// @dev checked by the onlyWhenActive modifier function lock() external override onlyMigrationManager { locked = true; emit Locked(); } /// Unlocks the contract /// @dev governance function called only by the migration manager or an admin /// @dev typically called by the registry contract upon unlocking all managed contracts function unlock() external override onlyMigrationManager { locked = false; emit Unlocked(); } /// Returns the contract locking status /// @return isLocked is a bool indicating the contract is locked function isLocked() external override view returns (bool) { return locked; } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/ManagedContract.sol pragma solidity 0.6.12; /// @title managed contract contract ManagedContract is IManagedContract, Lockable { /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {} /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() virtual override external {} } // File: contracts/StakingRewards.sol pragma solidity 0.6.12; contract StakingRewards is IStakingRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 annualCap; uint32 annualRateInPercentMille; uint32 defaultDelegatorsStakingRewardsPercentMille; uint32 maxDelegatorsStakingRewardsPercentMille; bool rewardAllocationActive; } Settings settings; IERC20 public token; struct StakingRewardsState { uint96 stakingRewardsPerWeight; uint96 unclaimedStakingRewards; uint32 lastAssigned; } StakingRewardsState public stakingRewardsState; uint256 public stakingRewardsContractBalance; struct GuardianStakingRewards { uint96 delegatorRewardsPerToken; uint96 lastStakingRewardsPerWeight; uint96 balance; uint96 claimed; } mapping(address => GuardianStakingRewards) public guardiansStakingRewards; struct GuardianRewardSettings { uint32 delegatorsStakingRewardsPercentMille; bool overrideDefault; } mapping(address => GuardianRewardSettings) public guardiansRewardSettings; struct DelegatorStakingRewards { uint96 balance; uint96 lastDelegatorRewardsPerToken; uint96 claimed; } mapping(address => DelegatorStakingRewards) public delegatorsStakingRewards; /// Constructor /// @dev the constructor does not migrate reward balances from the previous rewards contract /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _token is the token used for staking rewards /// @param annualRateInPercentMille is the annual rate in percent-mille /// @param annualCap is the annual staking rewards cap /// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille) /// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000) /// @param previousRewardsContract is the previous rewards contract address used for migration of guardians settings. address(0) indicates no guardian settings to migrate /// @param guardiansToMigrate is a list of guardian addresses to migrate their rewards settings constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _token, uint32 annualRateInPercentMille, uint96 annualCap, uint32 defaultDelegatorsStakingRewardsPercentMille, uint32 maxDelegatorsStakingRewardsPercentMille, IStakingRewards previousRewardsContract, address[] memory guardiansToMigrate ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_token) != address(0), "token must not be 0"); _setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap); setMaxDelegatorsStakingRewardsPercentMille(maxDelegatorsStakingRewardsPercentMille); setDefaultDelegatorsStakingRewardsPercentMille(defaultDelegatorsStakingRewardsPercentMille); token = _token; if (address(previousRewardsContract) != address(0)) { migrateGuardiansSettings(previousRewardsContract, guardiansToMigrate); } } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } modifier onlyDelegationsContract() { require(msg.sender == address(delegationsContract), "caller is not the delegations contract"); _; } /* * External functions */ /// Returns the current reward balance of the given address. /// @dev calculates the up to date balances (differ from the state) /// @param addr is the address to query /// @return delegatorStakingRewardsBalance the rewards awarded to the guardian role /// @return guardianStakingRewardsBalance the rewards awarded to the guardian role function getStakingRewardsBalance(address addr) external override view returns (uint256 delegatorStakingRewardsBalance, uint256 guardianStakingRewardsBalance) { (DelegatorStakingRewards memory delegatorStakingRewards,,) = getDelegatorStakingRewards(addr, block.timestamp); (GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(addr, block.timestamp); return (delegatorStakingRewards.balance, guardianStakingRewards.balance); } /// Claims the staking rewards balance of an addr, staking the rewards /// @dev Claimed rewards are staked in the staking contract using the distributeRewards interface /// @dev includes the rewards for both the delegator and guardian roles /// @dev calculates the up to date rewards prior to distribute them to the staking contract /// @param addr is the address to claim rewards for function claimStakingRewards(address addr) external override onlyWhenActive { (uint256 guardianRewards, uint256 delegatorRewards) = claimStakingRewardsLocally(addr); uint256 total = delegatorRewards.add(guardianRewards); if (total == 0) { return; } uint96 claimedGuardianRewards = guardiansStakingRewards[addr].claimed.add(guardianRewards); guardiansStakingRewards[addr].claimed = claimedGuardianRewards; uint96 claimedDelegatorRewards = delegatorsStakingRewards[addr].claimed.add(delegatorRewards); delegatorsStakingRewards[addr].claimed = claimedDelegatorRewards; require(token.approve(address(stakingContract), total), "claimStakingRewards: approve failed"); address[] memory addrs = new address[](1); addrs[0] = addr; uint256[] memory amounts = new uint256[](1); amounts[0] = total; stakingContract.distributeRewards(total, addrs, amounts); emit StakingRewardsClaimed(addr, delegatorRewards, guardianRewards, claimedDelegatorRewards, claimedGuardianRewards); } /// Returns the current global staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @return stakingRewardsPerWeight is the potential reward per 1E18 (TOKEN_BASE) committee weight assigned to a guardian was in the committee from day zero /// @return unclaimedStakingRewards is the of tokens that were assigned to participants and not claimed yet function getStakingRewardsState() public override view returns ( uint96 stakingRewardsPerWeight, uint96 unclaimedStakingRewards ) { (, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats(); (StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, settings); stakingRewardsPerWeight = _stakingRewardsState.stakingRewardsPerWeight; unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards; } /// Returns the current guardian staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @dev notice that the guardian rewards are the rewards for the guardian role as guardian and do not include delegation rewards /// @dev use getDelegatorStakingRewardsData to get the guardian's rewards as delegator /// @param guardian is the guardian to query /// @return balance is the staking rewards balance for the guardian role /// @return claimed is the staking rewards for the guardian role that were claimed /// @return delegatorRewardsPerToken is the potential reward per token (1E18 units) assigned to a guardian's delegator that delegated from day zero /// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last guardian update /// @return lastStakingRewardsPerWeight is the up to date stakingRewardsPerWeight used for the guardian state calculation /// @return stakingRewardsPerWeightDelta is the increment in stakingRewardsPerWeight since the last guardian update function getGuardianStakingRewardsData(address guardian) external override view returns ( uint256 balance, uint256 claimed, uint256 delegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta, uint256 lastStakingRewardsPerWeight, uint256 stakingRewardsPerWeightDelta ) { (GuardianStakingRewards memory rewards, uint256 _stakingRewardsPerWeightDelta, uint256 _delegatorRewardsPerTokenDelta) = getGuardianStakingRewards(guardian, block.timestamp); return (rewards.balance, rewards.claimed, rewards.delegatorRewardsPerToken, _delegatorRewardsPerTokenDelta, rewards.lastStakingRewardsPerWeight, _stakingRewardsPerWeightDelta); } /// Returns the current delegator staking rewards state /// @dev calculated to the latest block, may differ from the state read /// @param delegator is the delegator to query /// @return balance is the staking rewards balance for the delegator role /// @return claimed is the staking rewards for the delegator role that were claimed /// @return guardian is the guardian the delegator delegated to receiving a portion of the guardian staking rewards /// @return lastDelegatorRewardsPerToken is the up to date delegatorRewardsPerToken used for the delegator state calculation /// @return delegatorRewardsPerTokenDelta is the increment in delegatorRewardsPerToken since the last delegator update function getDelegatorStakingRewardsData(address delegator) external override view returns ( uint256 balance, uint256 claimed, address guardian, uint256 lastDelegatorRewardsPerToken, uint256 delegatorRewardsPerTokenDelta ) { (DelegatorStakingRewards memory rewards, address _guardian, uint256 _delegatorRewardsPerTokenDelta) = getDelegatorStakingRewards(delegator, block.timestamp); return (rewards.balance, rewards.claimed, _guardian, rewards.lastDelegatorRewardsPerToken, _delegatorRewardsPerTokenDelta); } /// Returns an estimation for the delegator and guardian staking rewards for a given duration /// @dev the returned value is an estimation, assuming no change in the PoS state /// @dev the period calculated for start from the current block time until the current time + duration. /// @param addr is the address to estimate rewards for /// @param duration is the duration to calculate for in seconds /// @return estimatedDelegatorStakingRewards is the estimated reward for the delegator role /// @return estimatedGuardianStakingRewards is the estimated reward for the guardian role function estimateFutureRewards(address addr, uint256 duration) external override view returns (uint256 estimatedDelegatorStakingRewards, uint256 estimatedGuardianStakingRewards) { (GuardianStakingRewards memory guardianRewardsNow,,) = getGuardianStakingRewards(addr, block.timestamp); (DelegatorStakingRewards memory delegatorRewardsNow,,) = getDelegatorStakingRewards(addr, block.timestamp); (GuardianStakingRewards memory guardianRewardsFuture,,) = getGuardianStakingRewards(addr, block.timestamp.add(duration)); (DelegatorStakingRewards memory delegatorRewardsFuture,,) = getDelegatorStakingRewards(addr, block.timestamp.add(duration)); estimatedDelegatorStakingRewards = delegatorRewardsFuture.balance.sub(delegatorRewardsNow.balance); estimatedGuardianStakingRewards = guardianRewardsFuture.balance.sub(guardianRewardsNow.balance); } /// Sets the guardian's delegators staking reward portion /// @dev by default uses the defaultDelegatorsStakingRewardsPercentMille /// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille) function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external override onlyWhenActive { require(delegatorRewardsPercentMille <= PERCENT_MILLIE_BASE, "delegatorRewardsPercentMille must be 100000 at most"); require(delegatorRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "delegatorRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille"); updateDelegatorStakingRewards(msg.sender); _setGuardianDelegatorsStakingRewardsPercentMille(msg.sender, delegatorRewardsPercentMille); } /// Returns a guardian's delegators staking reward portion /// @dev If not explicitly set, returns the defaultDelegatorsStakingRewardsPercentMille /// @return delegatorRewardsRatioPercentMille is the delegators portion in percent-mille function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external override view returns (uint256 delegatorRewardsRatioPercentMille) { return _getGuardianDelegatorsStakingRewardsPercentMille(guardian, settings); } /// Returns the amount of ORBS tokens in the staking rewards wallet allocated to staking rewards /// @dev The staking wallet balance must always larger than the allocated value /// @return allocated is the amount of tokens allocated in the staking rewards wallet function getStakingRewardsWalletAllocatedTokens() external override view returns (uint256 allocated) { (, uint96 unclaimedStakingRewards) = getStakingRewardsState(); return uint256(unclaimedStakingRewards).sub(stakingRewardsContractBalance); } /// Returns the current annual staking reward rate /// @dev calculated based on the current total committee weight /// @return annualRate is the current staking reward rate in percent-mille function getCurrentStakingRewardsRatePercentMille() external override view returns (uint256 annualRate) { (, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats(); annualRate = _getAnnualRewardPerWeight(totalCommitteeWeight, settings).mul(PERCENT_MILLIE_BASE).div(TOKEN_BASE); } /// Notifies an expected change in the committee membership of the guardian /// @dev Called only by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @dev triggers update of the global rewards state and the guardian rewards state /// @dev updates the rewards state based on the committee state prior to the change /// @param guardian is the guardian who's committee membership is updated /// @param weight is the weight of the guardian prior to the change /// @param totalCommitteeWeight is the total committee weight prior to the change /// @param inCommittee indicates whether the guardian was in the committee prior to the change /// @param inCommitteeAfter indicates whether the guardian is in the committee after the change function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external override onlyWhenActive onlyCommitteeContract { uint256 delegatedStake = delegationsContract.getDelegatedStake(guardian); Settings memory _settings = settings; StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings); _updateGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, weight, delegatedStake, _stakingRewardsState, _settings); } /// Notifies an expected change in a delegator and his guardian delegation state /// @dev Called only by: the Delegation contract /// @dev called upon expected change in a delegator's delegation state /// @dev triggers update of the global rewards state, the guardian rewards state and the delegator rewards state /// @dev on delegation change, updates also the new guardian and the delegator's lastDelegatorRewardsPerToken accordingly /// @param guardian is the delegator's guardian prior to the change /// @param guardianDelegatedStake is the delegated stake of the delegator's guardian prior to the change /// @param delegator is the delegator about to change delegation state /// @param delegatorStake is the stake of the delegator /// @param nextGuardian is the delegator's guardian after to the change /// @param nextGuardianDelegatedStake is the delegated stake of the delegator's guardian after to the change function delegationWillChange(address guardian, uint256 guardianDelegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external override onlyWhenActive onlyDelegationsContract { Settings memory _settings = settings; (bool inCommittee, uint256 weight, , uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian); StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings); GuardianStakingRewards memory guardianStakingRewards = _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, weight, guardianDelegatedStake, _stakingRewardsState, _settings); _updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianStakingRewards); if (nextGuardian != guardian) { (inCommittee, weight, , totalCommitteeWeight) = committeeContract.getMemberInfo(nextGuardian); GuardianStakingRewards memory nextGuardianStakingRewards = _updateGuardianStakingRewards(nextGuardian, inCommittee, inCommittee, weight, nextGuardianDelegatedStake, _stakingRewardsState, _settings); delegatorsStakingRewards[delegator].lastDelegatorRewardsPerToken = nextGuardianStakingRewards.delegatorRewardsPerToken; } } /* * Governance functions */ /// Activates staking rewards allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set to the previous contract deactivation time /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); stakingRewardsState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); StakingRewardsState memory _stakingRewardsState = updateStakingRewardsState(); settings.rewardAllocationActive = false; withdrawRewardsWalletAllocatedTokens(_stakingRewardsState); emit RewardDistributionDeactivated(); } /// Sets the default delegators staking reward portion /// @dev governance function called only by the functional manager /// @param defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille(0 - maxDelegatorsStakingRewardsPercentMille) function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager { require(defaultDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "defaultDelegatorsStakingRewardsPercentMille must not be larger than 100000"); require(defaultDelegatorsStakingRewardsPercentMille <= settings.maxDelegatorsStakingRewardsPercentMille, "defaultDelegatorsStakingRewardsPercentMille must not be larger than maxDelegatorsStakingRewardsPercentMille"); settings.defaultDelegatorsStakingRewardsPercentMille = defaultDelegatorsStakingRewardsPercentMille; emit DefaultDelegatorsStakingRewardsChanged(defaultDelegatorsStakingRewardsPercentMille); } /// Returns the default delegators staking reward portion /// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille function getDefaultDelegatorsStakingRewardsPercentMille() public override view returns (uint32) { return settings.defaultDelegatorsStakingRewardsPercentMille; } /// Sets the maximum delegators staking reward portion /// @dev governance function called only by the functional manager /// @param maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille(0 - 100,000) function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) public override onlyFunctionalManager { require(maxDelegatorsStakingRewardsPercentMille <= PERCENT_MILLIE_BASE, "maxDelegatorsStakingRewardsPercentMille must not be larger than 100000"); settings.maxDelegatorsStakingRewardsPercentMille = maxDelegatorsStakingRewardsPercentMille; emit MaxDelegatorsStakingRewardsChanged(maxDelegatorsStakingRewardsPercentMille); } /// Returns the default delegators staking reward portion /// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille function getMaxDelegatorsStakingRewardsPercentMille() public override view returns (uint32) { return settings.maxDelegatorsStakingRewardsPercentMille; } /// Sets the annual rate and cap for the staking reward /// @dev governance function called only by the functional manager /// @param annualRateInPercentMille is the annual rate in percent-mille /// @param annualCap is the annual staking rewards cap function setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) external override onlyFunctionalManager { updateStakingRewardsState(); return _setAnnualStakingRewardsRate(annualRateInPercentMille, annualCap); } /// Returns the annual staking reward rate /// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille function getAnnualStakingRewardsRatePercentMille() external override view returns (uint32) { return settings.annualRateInPercentMille; } /// Returns the annual staking rewards cap /// @return annualStakingRewardsCap is the annual rate in percent-mille function getAnnualStakingRewardsCap() external override view returns (uint256) { return settings.annualCap; } /// Checks if rewards allocation is active /// @return rewardAllocationActive is a bool that indicates that rewards allocation is active function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Returns the contract's settings /// @return annualStakingRewardsCap is the annual rate in percent-mille /// @return annualStakingRewardsRatePercentMille is the annual rate in percent-mille /// @return defaultDelegatorsStakingRewardsPercentMille is the default delegators portion in percent-mille /// @return maxDelegatorsStakingRewardsPercentMille is the maximum delegators portion in percent-mille /// @return rewardAllocationActive is a bool that indicates that rewards allocation is active function getSettings() external override view returns ( uint annualStakingRewardsCap, uint32 annualStakingRewardsRatePercentMille, uint32 defaultDelegatorsStakingRewardsPercentMille, uint32 maxDelegatorsStakingRewardsPercentMille, bool rewardAllocationActive ) { Settings memory _settings = settings; annualStakingRewardsCap = _settings.annualCap; annualStakingRewardsRatePercentMille = _settings.annualRateInPercentMille; defaultDelegatorsStakingRewardsPercentMille = _settings.defaultDelegatorsStakingRewardsPercentMille; maxDelegatorsStakingRewardsPercentMille = _settings.maxDelegatorsStakingRewardsPercentMille; rewardAllocationActive = _settings.rewardAllocationActive; } /// Migrates the staking rewards balance of the given addresses to a new staking rewards contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param addrs is the list of addresses to migrate function migrateRewardsBalance(address[] calldata addrs) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IStakingRewards currentRewardsContract = IStakingRewards(getStakingRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalAmount = 0; uint256[] memory guardianRewards = new uint256[](addrs.length); uint256[] memory delegatorRewards = new uint256[](addrs.length); for (uint i = 0; i < addrs.length; i++) { (guardianRewards[i], delegatorRewards[i]) = claimStakingRewardsLocally(addrs[i]); totalAmount = totalAmount.add(guardianRewards[i]).add(delegatorRewards[i]); } require(token.approve(address(currentRewardsContract), totalAmount), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(addrs, guardianRewards, delegatorRewards, totalAmount); for (uint i = 0; i < addrs.length; i++) { emit StakingRewardsBalanceMigrated(addrs[i], guardianRewards[i], delegatorRewards[i], address(currentRewardsContract)); } } /// Accepts addresses balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param addrs is the list migrated addresses /// @param migratedGuardianStakingRewards is the list of received guardian rewards balance for each address /// @param migratedDelegatorStakingRewards is the list of received delegator rewards balance for each address /// @param totalAmount is the total amount of staking rewards migrated for all addresses in the list. Must match the sum of migratedGuardianStakingRewards and migratedDelegatorStakingRewards lists. function acceptRewardsBalanceMigration(address[] calldata addrs, uint256[] calldata migratedGuardianStakingRewards, uint256[] calldata migratedDelegatorStakingRewards, uint256 totalAmount) external override { uint256 _totalAmount = 0; for (uint i = 0; i < addrs.length; i++) { _totalAmount = _totalAmount.add(migratedGuardianStakingRewards[i]).add(migratedDelegatorStakingRewards[i]); } require(totalAmount == _totalAmount, "totalAmount does not match sum of rewards"); if (totalAmount > 0) { require(token.transferFrom(msg.sender, address(this), totalAmount), "acceptRewardBalanceMigration: transfer failed"); } for (uint i = 0; i < addrs.length; i++) { guardiansStakingRewards[addrs[i]].balance = guardiansStakingRewards[addrs[i]].balance.add(migratedGuardianStakingRewards[i]); delegatorsStakingRewards[addrs[i]].balance = delegatorsStakingRewards[addrs[i]].balance.add(migratedDelegatorStakingRewards[i]); emit StakingRewardsBalanceMigrationAccepted(msg.sender, addrs[i], migratedGuardianStakingRewards[i], migratedDelegatorStakingRewards[i]); } stakingRewardsContractBalance = stakingRewardsContractBalance.add(totalAmount); stakingRewardsState.unclaimedStakingRewards = stakingRewardsState.unclaimedStakingRewards.add(totalAmount); } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "StakingRewards::emergencyWithdraw - transfer failed"); } /* * Private functions */ // Global state /// Returns the annual reward per weight /// @dev calculates the current annual rewards per weight based on the annual rate and annual cap function _getAnnualRewardPerWeight(uint256 totalCommitteeWeight, Settings memory _settings) private pure returns (uint256) { return totalCommitteeWeight == 0 ? 0 : Math.min(uint256(_settings.annualRateInPercentMille).mul(TOKEN_BASE).div(PERCENT_MILLIE_BASE), uint256(_settings.annualCap).mul(TOKEN_BASE).div(totalCommitteeWeight)); } /// Calculates the added rewards per weight for the given duration based on the committee data /// @param totalCommitteeWeight is the current committee total weight /// @param duration is the duration to calculate for in seconds /// @param _settings is the contract settings function calcStakingRewardPerWeightDelta(uint256 totalCommitteeWeight, uint duration, Settings memory _settings) private pure returns (uint256 stakingRewardsPerWeightDelta) { stakingRewardsPerWeightDelta = 0; if (totalCommitteeWeight > 0) { uint annualRewardPerWeight = _getAnnualRewardPerWeight(totalCommitteeWeight, _settings); stakingRewardsPerWeightDelta = annualRewardPerWeight.mul(duration).div(365 days); } } /// Returns the up global staking rewards state for a specific time /// @dev receives the relevant committee data /// @dev for future time calculations assumes no change in the committee data /// @param totalCommitteeWeight is the current committee total weight /// @param currentTime is the time to calculate the rewards for /// @param _settings is the contract settings function _getStakingRewardsState(uint256 totalCommitteeWeight, uint256 currentTime, Settings memory _settings) private view returns (StakingRewardsState memory _stakingRewardsState, uint256 allocatedRewards) { _stakingRewardsState = stakingRewardsState; if (_settings.rewardAllocationActive) { uint delta = calcStakingRewardPerWeightDelta(totalCommitteeWeight, currentTime.sub(stakingRewardsState.lastAssigned), _settings); _stakingRewardsState.stakingRewardsPerWeight = stakingRewardsState.stakingRewardsPerWeight.add(delta); _stakingRewardsState.lastAssigned = uint32(currentTime); allocatedRewards = delta.mul(totalCommitteeWeight).div(TOKEN_BASE); _stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.add(allocatedRewards); } } /// Updates the global staking rewards /// @dev calculated to the latest block, may differ from the state read /// @dev uses the _getStakingRewardsState function /// @param totalCommitteeWeight is the current committee total weight /// @param _settings is the contract settings /// @return _stakingRewardsState is the updated global staking rewards struct function _updateStakingRewardsState(uint256 totalCommitteeWeight, Settings memory _settings) private returns (StakingRewardsState memory _stakingRewardsState) { if (!_settings.rewardAllocationActive) { return stakingRewardsState; } uint allocatedRewards; (_stakingRewardsState, allocatedRewards) = _getStakingRewardsState(totalCommitteeWeight, block.timestamp, _settings); stakingRewardsState = _stakingRewardsState; emit StakingRewardsAllocated(allocatedRewards, _stakingRewardsState.stakingRewardsPerWeight); } /// Updates the global staking rewards /// @dev calculated to the latest block, may differ from the state read /// @dev queries the committee state from the committee contract /// @dev uses the _updateStakingRewardsState function /// @return _stakingRewardsState is the updated global staking rewards struct function updateStakingRewardsState() private returns (StakingRewardsState memory _stakingRewardsState) { (, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats(); return _updateStakingRewardsState(totalCommitteeWeight, settings); } // Guardian state /// Returns the current guardian staking rewards state /// @dev receives the relevant committee and guardian data along with the global updated global state /// @dev calculated to the latest block, may differ from the state read /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param inCommitteeAfter indicates whether after a potential change the guardian is in the committee /// @param guardianWeight is the guardian committee weight /// @param guardianDelegatedStake is the guardian delegated stake /// @param _stakingRewardsState is the updated global staking rewards state /// @param _settings is the contract settings /// @return guardianStakingRewards is the updated guardian staking rewards state /// @return rewardsAdded is the amount awarded to the guardian since the last update /// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update /// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update function _getGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 rewardsAdded, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) { guardianStakingRewards = guardiansStakingRewards[guardian]; if (inCommittee) { stakingRewardsPerWeightDelta = uint256(_stakingRewardsState.stakingRewardsPerWeight).sub(guardianStakingRewards.lastStakingRewardsPerWeight); uint256 totalRewards = stakingRewardsPerWeightDelta.mul(guardianWeight); uint256 delegatorRewardsRatioPercentMille = _getGuardianDelegatorsStakingRewardsPercentMille(guardian, _settings); delegatorRewardsPerTokenDelta = guardianDelegatedStake == 0 ? 0 : totalRewards .div(guardianDelegatedStake) .mul(delegatorRewardsRatioPercentMille) .div(PERCENT_MILLIE_BASE); uint256 guardianCutPercentMille = PERCENT_MILLIE_BASE.sub(delegatorRewardsRatioPercentMille); rewardsAdded = totalRewards .mul(guardianCutPercentMille) .div(PERCENT_MILLIE_BASE) .div(TOKEN_BASE); guardianStakingRewards.delegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken.add(delegatorRewardsPerTokenDelta); guardianStakingRewards.balance = guardianStakingRewards.balance.add(rewardsAdded); } guardianStakingRewards.lastStakingRewardsPerWeight = inCommitteeAfter ? _stakingRewardsState.stakingRewardsPerWeight : 0; } /// Returns the guardian staking rewards state for a given time /// @dev if the time to estimate is in the future, estimates the rewards for the given time /// @dev for future time estimation assumes no change in the committee and the guardian state /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the rewards for /// @return guardianStakingRewards is the guardian staking rewards state updated to the give time /// @return stakingRewardsPerWeightDelta is the delta added to the stakingRewardsPerWeight since the last update /// @return delegatorRewardsPerTokenDelta is the delta added to the guardian's delegatorRewardsPerToken since the last update function getGuardianStakingRewards(address guardian, uint256 currentTime) private view returns (GuardianStakingRewards memory guardianStakingRewards, uint256 stakingRewardsPerWeightDelta, uint256 delegatorRewardsPerTokenDelta) { Settings memory _settings = settings; (bool inCommittee, uint256 guardianWeight, ,uint256 totalCommitteeWeight) = committeeContract.getMemberInfo(guardian); uint256 guardianDelegatedStake = delegationsContract.getDelegatedStake(guardian); (StakingRewardsState memory _stakingRewardsState,) = _getStakingRewardsState(totalCommitteeWeight, currentTime, _settings); (guardianStakingRewards,,stakingRewardsPerWeightDelta,delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings); } /// Updates a guardian staking rewards state /// @dev receives the relevant committee and guardian data along with the global updated global state /// @dev updates the global staking rewards state prior to calculating the guardian's /// @dev uses _getGuardianStakingRewards /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian was in the committee prior to the change /// @param inCommitteeAfter indicates whether the guardian is in the committee after the change /// @param guardianWeight is the committee weight of the guardian prior to the change /// @param guardianDelegatedStake is the delegated stake of the guardian prior to the change /// @param _stakingRewardsState is the updated global staking rewards state /// @param _settings is the contract settings /// @return guardianStakingRewards is the updated guardian staking rewards state function _updateGuardianStakingRewards(address guardian, bool inCommittee, bool inCommitteeAfter, uint256 guardianWeight, uint256 guardianDelegatedStake, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) { uint256 guardianStakingRewardsAdded; uint256 stakingRewardsPerWeightDelta; uint256 delegatorRewardsPerTokenDelta; (guardianStakingRewards, guardianStakingRewardsAdded, stakingRewardsPerWeightDelta, delegatorRewardsPerTokenDelta) = _getGuardianStakingRewards(guardian, inCommittee, inCommitteeAfter, guardianWeight, guardianDelegatedStake, _stakingRewardsState, _settings); guardiansStakingRewards[guardian] = guardianStakingRewards; emit GuardianStakingRewardsAssigned(guardian, guardianStakingRewardsAdded, guardianStakingRewards.claimed.add(guardianStakingRewards.balance), guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta, _stakingRewardsState.stakingRewardsPerWeight, stakingRewardsPerWeightDelta); } /// Updates a guardian staking rewards state /// @dev queries the relevant guardian and committee data from the committee contract /// @dev uses _updateGuardianStakingRewards /// @param guardian is the guardian to update /// @param _stakingRewardsState is the updated global staking rewards state /// @param _settings is the contract settings /// @return guardianStakingRewards is the updated guardian staking rewards state function updateGuardianStakingRewards(address guardian, StakingRewardsState memory _stakingRewardsState, Settings memory _settings) private returns (GuardianStakingRewards memory guardianStakingRewards) { (bool inCommittee, uint256 guardianWeight,,) = committeeContract.getMemberInfo(guardian); return _updateGuardianStakingRewards(guardian, inCommittee, inCommittee, guardianWeight, delegationsContract.getDelegatedStake(guardian), _stakingRewardsState, _settings); } // Delegator state /// Returns the current delegator staking rewards state /// @dev receives the relevant delegator data along with the delegator's current guardian updated global state /// @dev calculated to the latest block, may differ from the state read /// @param delegator is the delegator to query /// @param delegatorStake is the stake of the delegator /// @param guardianStakingRewards is the updated guardian staking rewards state /// @return delegatorStakingRewards is the updated delegator staking rewards state /// @return delegatorRewardsAdded is the amount awarded to the delegator since the last update /// @return delegatorRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update function _getDelegatorStakingRewards(address delegator, uint256 delegatorStake, GuardianStakingRewards memory guardianStakingRewards) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, uint256 delegatorRewardsAdded, uint256 delegatorRewardsPerTokenDelta) { delegatorStakingRewards = delegatorsStakingRewards[delegator]; delegatorRewardsPerTokenDelta = uint256(guardianStakingRewards.delegatorRewardsPerToken) .sub(delegatorStakingRewards.lastDelegatorRewardsPerToken); delegatorRewardsAdded = delegatorRewardsPerTokenDelta .mul(delegatorStake) .div(TOKEN_BASE); delegatorStakingRewards.balance = delegatorStakingRewards.balance.add(delegatorRewardsAdded); delegatorStakingRewards.lastDelegatorRewardsPerToken = guardianStakingRewards.delegatorRewardsPerToken; } /// Returns the delegator staking rewards state for a given time /// @dev if the time to estimate is in the future, estimates the rewards for the given time /// @dev for future time estimation assumes no change in the committee, delegation and the delegator state /// @param delegator is the delegator to query /// @param currentTime is the time to calculate the rewards for /// @return delegatorStakingRewards is the updated delegator staking rewards state /// @return guardian is the guardian the delegator delegated to /// @return delegatorStakingRewardsPerTokenDelta is the delta added to the delegator's delegatorRewardsPerToken since the last update function getDelegatorStakingRewards(address delegator, uint256 currentTime) private view returns (DelegatorStakingRewards memory delegatorStakingRewards, address guardian, uint256 delegatorStakingRewardsPerTokenDelta) { uint256 delegatorStake; (guardian, delegatorStake) = delegationsContract.getDelegationInfo(delegator); (GuardianStakingRewards memory guardianStakingRewards,,) = getGuardianStakingRewards(guardian, currentTime); (delegatorStakingRewards,,delegatorStakingRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards); } /// Updates a delegator staking rewards state /// @dev receives the relevant delegator data along with the delegator's current guardian updated global state /// @dev updates the guardian staking rewards state prior to calculating the delegator's /// @dev uses _getDelegatorStakingRewards /// @param delegator is the delegator to update /// @param delegatorStake is the stake of the delegator /// @param guardianStakingRewards is the updated guardian staking rewards state function _updateDelegatorStakingRewards(address delegator, uint256 delegatorStake, address guardian, GuardianStakingRewards memory guardianStakingRewards) private { uint256 delegatorStakingRewardsAdded; uint256 delegatorRewardsPerTokenDelta; DelegatorStakingRewards memory delegatorStakingRewards; (delegatorStakingRewards, delegatorStakingRewardsAdded, delegatorRewardsPerTokenDelta) = _getDelegatorStakingRewards(delegator, delegatorStake, guardianStakingRewards); delegatorsStakingRewards[delegator] = delegatorStakingRewards; emit DelegatorStakingRewardsAssigned(delegator, delegatorStakingRewardsAdded, delegatorStakingRewards.claimed.add(delegatorStakingRewards.balance), guardian, guardianStakingRewards.delegatorRewardsPerToken, delegatorRewardsPerTokenDelta); } /// Updates a delegator staking rewards state /// @dev queries the relevant delegator and committee data from the committee contract and delegation contract /// @dev uses _updateDelegatorStakingRewards /// @param delegator is the delegator to update function updateDelegatorStakingRewards(address delegator) private { Settings memory _settings = settings; (, , uint totalCommitteeWeight) = committeeContract.getCommitteeStats(); StakingRewardsState memory _stakingRewardsState = _updateStakingRewardsState(totalCommitteeWeight, _settings); (address guardian, uint delegatorStake) = delegationsContract.getDelegationInfo(delegator); GuardianStakingRewards memory guardianRewards = updateGuardianStakingRewards(guardian, _stakingRewardsState, _settings); _updateDelegatorStakingRewards(delegator, delegatorStake, guardian, guardianRewards); } // Guardian settings /// Returns the guardian's delegator portion in percent-mille /// @dev if no explicit value was set by the guardian returns the default value /// @dev enforces the maximum delegators staking rewards cut function _getGuardianDelegatorsStakingRewardsPercentMille(address guardian, Settings memory _settings) private view returns (uint256 delegatorRewardsRatioPercentMille) { GuardianRewardSettings memory guardianSettings = guardiansRewardSettings[guardian]; delegatorRewardsRatioPercentMille = guardianSettings.overrideDefault ? guardianSettings.delegatorsStakingRewardsPercentMille : _settings.defaultDelegatorsStakingRewardsPercentMille; return Math.min(delegatorRewardsRatioPercentMille, _settings.maxDelegatorsStakingRewardsPercentMille); } /// Migrates a list of guardians' delegators portion setting from a previous staking rewards contract /// @dev called by the constructor function migrateGuardiansSettings(IStakingRewards previousRewardsContract, address[] memory guardiansToMigrate) private { for (uint i = 0; i < guardiansToMigrate.length; i++) { _setGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i], uint32(previousRewardsContract.getGuardianDelegatorsStakingRewardsPercentMille(guardiansToMigrate[i]))); } } // Governance and misc. /// Sets the annual rate and cap for the staking reward /// @param annualRateInPercentMille is the annual rate in percent-mille /// @param annualCap is the annual staking rewards cap function _setAnnualStakingRewardsRate(uint32 annualRateInPercentMille, uint96 annualCap) private { Settings memory _settings = settings; _settings.annualRateInPercentMille = annualRateInPercentMille; _settings.annualCap = annualCap; settings = _settings; emit AnnualStakingRewardsRateChanged(annualRateInPercentMille, annualCap); } /// Sets the guardian's delegators staking reward portion /// @param guardian is the guardian to set /// @param delegatorRewardsPercentMille is the delegators portion in percent-mille (0 - maxDelegatorsStakingRewardsPercentMille) function _setGuardianDelegatorsStakingRewardsPercentMille(address guardian, uint32 delegatorRewardsPercentMille) private { guardiansRewardSettings[guardian] = GuardianRewardSettings({ overrideDefault: true, delegatorsStakingRewardsPercentMille: delegatorRewardsPercentMille }); emit GuardianDelegatorsStakingRewardsPercentMilleUpdated(guardian, delegatorRewardsPercentMille); } /// Claims an addr staking rewards and update its rewards state without transferring the rewards /// @dev used by claimStakingRewards and migrateRewardsBalance /// @param addr is the address to claim rewards for /// @return guardianRewards is the claimed guardian rewards balance /// @return delegatorRewards is the claimed delegator rewards balance function claimStakingRewardsLocally(address addr) private returns (uint256 guardianRewards, uint256 delegatorRewards) { updateDelegatorStakingRewards(addr); guardianRewards = guardiansStakingRewards[addr].balance; guardiansStakingRewards[addr].balance = 0; delegatorRewards = delegatorsStakingRewards[addr].balance; delegatorsStakingRewards[addr].balance = 0; uint256 total = delegatorRewards.add(guardianRewards); StakingRewardsState memory _stakingRewardsState = stakingRewardsState; uint256 _stakingRewardsContractBalance = stakingRewardsContractBalance; if (total > _stakingRewardsContractBalance) { _stakingRewardsContractBalance = withdrawRewardsWalletAllocatedTokens(_stakingRewardsState); } stakingRewardsContractBalance = _stakingRewardsContractBalance.sub(total); stakingRewardsState.unclaimedStakingRewards = _stakingRewardsState.unclaimedStakingRewards.sub(total); } /// Withdraws the tokens that were allocated to the contract from the staking rewards wallet /// @dev used as part of the migration flow to withdraw all the funds allocated for participants before updating the wallet client to a new contract /// @param _stakingRewardsState is the updated global staking rewards state function withdrawRewardsWalletAllocatedTokens(StakingRewardsState memory _stakingRewardsState) private returns (uint256 _stakingRewardsContractBalance){ _stakingRewardsContractBalance = stakingRewardsContractBalance; uint256 allocated = _stakingRewardsState.unclaimedStakingRewards.sub(_stakingRewardsContractBalance); stakingRewardsWallet.withdraw(allocated); _stakingRewardsContractBalance = _stakingRewardsContractBalance.add(allocated); stakingRewardsContractBalance = _stakingRewardsContractBalance; } /* * Contracts topology / registry interface */ ICommittee committeeContract; IDelegations delegationsContract; IProtocolWallet stakingRewardsWallet; IStakingContract stakingContract; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); delegationsContract = IDelegations(getDelegationsContract()); stakingRewardsWallet = IProtocolWallet(getStakingRewardsWallet()); stakingContract = IStakingContract(getStakingContract()); } }
Deactivates fees and bootstrap allocation @dev governance function called only by the migration manager @dev guardians updates remain active based on the current perMember value
function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); StakingRewardsState memory _stakingRewardsState = updateStakingRewardsState(); settings.rewardAllocationActive = false; withdrawRewardsWalletAllocatedTokens(_stakingRewardsState); emit RewardDistributionDeactivated(); }
450,165
[ 1, 758, 11422, 815, 1656, 281, 471, 7065, 13481, 225, 314, 1643, 82, 1359, 445, 2566, 1338, 635, 326, 6333, 3301, 225, 11026, 19657, 4533, 7232, 2695, 2511, 603, 326, 783, 1534, 4419, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18790, 17631, 1060, 9003, 1435, 3903, 3849, 1338, 10224, 1318, 288, 203, 3639, 2583, 12, 4272, 18, 266, 2913, 17353, 3896, 16, 315, 266, 2913, 7006, 353, 1818, 443, 18836, 8863, 203, 203, 3639, 934, 6159, 17631, 14727, 1119, 3778, 389, 334, 6159, 17631, 14727, 1119, 273, 1089, 510, 6159, 17631, 14727, 1119, 5621, 203, 203, 3639, 1947, 18, 266, 2913, 17353, 3896, 273, 629, 31, 203, 203, 3639, 598, 9446, 17631, 14727, 16936, 29392, 5157, 24899, 334, 6159, 17631, 14727, 1119, 1769, 203, 203, 3639, 3626, 534, 359, 1060, 9003, 758, 18836, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } /** * @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 ILendingPoolAddressesProviderV2 { 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 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; } 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} } interface ILendingPoolV2 { /** * @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 **/ function withdraw( address asset, uint256 amount, address to ) external; /** * @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 **/ function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; /** * @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 (ILendingPoolAddressesProviderV2); function setPause(bool val) external; function paused() external view returns (bool); } /************ @title IPriceOracleGetterAave interface @notice Interface for the Aave price oracle.*/ abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract IAaveProtocolDataProviderV2 { struct TokenData { string symbol; address tokenAddress; } function getAllReservesTokens() external virtual view returns (TokenData[] memory); function getAllATokens() external virtual view returns (TokenData[] memory); function getReserveConfigurationData(address asset) external virtual 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 virtual 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 virtual 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 virtual view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external 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 decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { 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); } 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"); 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); } } } } 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) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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(ERC20 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"); } } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } modifier onlyAdmin() { require(admin == msg.sender); _; } constructor() public { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract AaveHelperV2 is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; uint public constant STABLE_ID = 1; uint public constant VARIABLE_ID = 2; /// @notice Calculates the gas cost for transaction /// @param _oracleAddress address of oracle used /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(address _oracleAddress, uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(_oracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); gasCost = _gasCost; } // gas cost can't go over 10% of the whole amount if (gasCost > (_amount / 10)) { gasCost = _amount / 10; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) internal { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) internal { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } function getDataProvider(address _market) internal view returns(IAaveProtocolDataProviderV2) { return IAaveProtocolDataProviderV2(ILendingPoolAddressesProviderV2(_market).getAddress(0x0100000000000000000000000000000000000000000000000000000000000000)); } } contract AaveSafetyRatioV2 is AaveHelperV2 { function getSafetyRatio(address _market, address _user) public view returns(uint256) { ILendingPoolV2 lendingPool = ILendingPoolV2(ILendingPoolAddressesProviderV2(_market).getLendingPool()); (,uint256 totalDebtETH,uint256 availableBorrowsETH,,,) = lendingPool.getUserAccountData(_user); if (totalDebtETH == 0) return uint256(0); return wdiv(add(totalDebtETH, availableBorrowsETH), totalDebtETH); } } contract AaveLoanInfoV2 is AaveSafetyRatioV2 { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowStableAmounts; uint256[] borrowVariableAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRateVariable; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; bool borrowinEnabled; bool stableBorrowRateEnabled; } struct ReserveData { uint256 availableLiquidity; uint256 totalStableDebt; uint256 totalVariableDebt; uint256 liquidityRate; uint256 variableBorrowRate; uint256 stableBorrowRate; } struct UserToken { address token; uint256 balance; uint256 borrowsStable; uint256 borrowsVariable; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user function getRatio(address _market, address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_market, _user); } /// @notice Fetches Aave prices for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address _market, address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); prices = IPriceOracleGetterAave(priceOracleAddress).getAssetsPrices(_tokens); } /// @notice Fetches Aave collateral factors for tokens /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address _market, address[] memory _tokens) public view returns (uint256[] memory collFactors) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,,,,,,,) = dataProvider.getReserveConfigurationData(_tokens[i]); } } function getTokenBalances(address _market, address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrowsStable, userTokens[i].borrowsVariable,,,,,,userTokens[i].enabledAsCollateral) = dataProvider.getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address _market, address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_market, _users[i]); } } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,,,,,,,) = dataProvider.getReserveConfigurationData(_tokenAddresses[i]); (address aToken,,) = dataProvider.getReserveTokensAddresses(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: aToken, underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } function getTokenInfoFull(IAaveProtocolDataProviderV2 _dataProvider, address _priceOracleAddress, address _token) private view returns(TokenInfoFull memory _tokenInfo) { ( , // uint256 decimals uint256 ltv, uint256 liquidationThreshold, , // uint256 liquidationBonus , // uint256 reserveFactor bool usageAsCollateralEnabled, bool borrowinEnabled, bool stableBorrowRateEnabled, , // bool isActive // bool isFrozen ) = _dataProvider.getReserveConfigurationData(_token); ReserveData memory t; ( t.availableLiquidity, t.totalStableDebt, t.totalVariableDebt, t.liquidityRate, t.variableBorrowRate, t.stableBorrowRate, , , , ) = _dataProvider.getReserveData(_token); (address aToken,,) = _dataProvider.getReserveTokensAddresses(_token); uint price = IPriceOracleGetterAave(_priceOracleAddress).getAssetPrice(_token); _tokenInfo = TokenInfoFull({ aTokenAddress: aToken, underlyingTokenAddress: _token, supplyRate: t.liquidityRate, borrowRateVariable: t.variableBorrowRate, borrowRateStable: t.stableBorrowRate, totalSupply: ERC20(aToken).totalSupply(), availableLiquidity: t.availableLiquidity, totalBorrow: t.totalVariableDebt+t.totalStableDebt, collateralFactor: ltv, liquidationRatio: liquidationThreshold, price: price, usageAsCollateralEnabled: usageAsCollateralEnabled, borrowinEnabled: borrowinEnabled, stableBorrowRateEnabled: stableBorrowRateEnabled }); } /// @notice Information about reserves /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address _market, address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { tokens[i] = getTokenInfoFull(dataProvider, priceOracleAddress, _tokenAddresses[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _market, address _user) public view returns (LoanData memory data) { IAaveProtocolDataProviderV2 dataProvider = getDataProvider(_market); address priceOracleAddress = ILendingPoolAddressesProviderV2(_market).getPriceOracle(); IAaveProtocolDataProviderV2.TokenData[] memory reserves = dataProvider.getAllReservesTokens(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowStableAmounts: new uint[](reserves.length), borrowVariableAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowStablePos = 0; uint64 borrowVariablePos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i].tokenAddress; (uint256 aTokenBalance, uint256 borrowsStable, uint256 borrowsVariable,,,,,,) = dataProvider.getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserve); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowsStable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsStable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowStablePos] = reserve; data.borrowStableAmounts[borrowStablePos] = userBorrowBalanceEth; borrowStablePos++; } // Sum up debt in Eth if (borrowsVariable > 0) { uint256 userBorrowBalanceEth = wmul(borrowsVariable, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowVariablePos] = reserve; data.borrowVariableAmounts[borrowVariablePos] = userBorrowBalanceEth; borrowVariablePos++; } } data.ratio = uint128(getSafetyRatio(_market, _user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _market Address of LendingPoolAddressesProvider for specific market /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address _market, address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_market, _users[i]); } } }
stores the reserve configurationthe liquidity index. Expressed in rayvariable borrow index. Expressed in raythe current supply rate. Expressed in raythe current variable borrow rate. Expressed in raythe current stable borrow rate. Expressed in raytokens addressesaddress of the interest rate strategythe id of the reserve. Represents the position in the list of the active reserves
function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } } struct ReserveData { ReserveConfigurationMap configuration; uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 currentLiquidityRate; uint128 currentVariableBorrowRate; uint128 currentStableBorrowRate; uint40 lastUpdateTimestamp; address aTokenAddress; address stableDebtTokenAddress; address variableDebtTokenAddress; address interestRateStrategyAddress; uint8 id; }
13,684,732
[ 1, 19632, 326, 20501, 1664, 5787, 4501, 372, 24237, 770, 18, 7784, 4638, 316, 14961, 6105, 29759, 770, 18, 7784, 4638, 316, 14961, 5787, 783, 14467, 4993, 18, 7784, 4638, 316, 14961, 5787, 783, 2190, 29759, 4993, 18, 7784, 4638, 316, 14961, 5787, 783, 14114, 29759, 4993, 18, 7784, 4638, 316, 14961, 7860, 6138, 2867, 434, 326, 16513, 4993, 6252, 5787, 612, 434, 326, 20501, 18, 868, 6706, 87, 326, 1754, 316, 326, 666, 434, 326, 2695, 400, 264, 3324, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 12, 11890, 5034, 389, 8949, 13, 3903, 5024, 31, 203, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 3903, 5024, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 97, 203, 203, 203, 203, 97, 203, 203, 225, 1958, 1124, 6527, 751, 288, 203, 565, 1124, 6527, 1750, 863, 1664, 31, 203, 565, 2254, 10392, 4501, 372, 24237, 1016, 31, 203, 565, 2254, 10392, 2190, 38, 15318, 1016, 31, 203, 565, 2254, 10392, 783, 48, 18988, 24237, 4727, 31, 203, 565, 2254, 10392, 783, 3092, 38, 15318, 4727, 31, 203, 565, 2254, 10392, 783, 30915, 38, 15318, 4727, 31, 203, 565, 2254, 7132, 1142, 1891, 4921, 31, 203, 565, 1758, 279, 1345, 1887, 31, 203, 565, 1758, 14114, 758, 23602, 1345, 1887, 31, 203, 565, 1758, 2190, 758, 23602, 1345, 1887, 31, 203, 565, 1758, 16513, 4727, 4525, 1887, 31, 203, 565, 2254, 28, 612, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // solhint-disable /* This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol Alterations: * Make the counter public, so that we can use it in our custom mint function * Removed ERC721Burnable parent contract, but added our own custom burn function. * Removed original "mint" function, because we have a custom one. * Removed default initialization functions, because they set msg.sender as the owner, which we do not want, because we use a deployer account, which is separate from the protocol owner. */ pragma solidity 0.6.12; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to aother accounts */ contract ERC721PresetMinterPauserAutoIdUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC721PausableUpgradeSafe { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter public _tokenIdTracker; /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721PausableUpgradeSafe) { super._beforeTokenTransfer(from, to, tokenId); } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.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, _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; } pragma solidity ^0.6.0; import "../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. */ 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; } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; import "../../Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; function __ERC721_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name, symbol); } function __ERC721_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view override returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If a base URI is set (via {_setBaseURI}), it is added as a prefix to the * token's own URI (via {_setTokenURI}). * * If there is a base URI but no token URI, the token's ID will be used as * its URI when appending it to the base URI. This pattern for autogenerated * token URIs can lead to large gas savings. * * .Examples * |=== * |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()` * | "" * | "" * | "" * | "" * | "token.uri/123" * | "token.uri/123" * | "token.uri/" * | "123" * | "token.uri/123" * | "token.uri/" * | "" * | "token.uri/<tokenId>" * |=== * * Requirements: * * - `tokenId` must exist. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ 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 Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ 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 Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ 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 the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ 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 the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ 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 Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: If all token IDs share a prefix (for example, if your URIs look like * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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 { } uint256[41] private __gap; } pragma solidity ^0.6.0; import "./ERC721.sol"; import "../../utils/Pausable.sol"; import "../../Initializable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe { function __ERC721Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); } function __ERC721Pausable_init_unchained() internal initializer { } /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } uint256[50] private __gap; } 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; } pragma solidity ^0.6.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.0.0, only sets of type `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]; } // 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(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(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(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(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)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.6.2; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } pragma solidity ^0.6.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity ^0.6.0; import "./IERC165.sol"; import "../Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165UpgradeSafe is Initializable, IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } pragma solidity ^0.6.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity ^0.6.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); } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../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 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; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ISeniorPool.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../library/StakingRewardsVesting.sol"; contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using ConfigHelper for GoldfinchConfig; using StakingRewardsVesting for StakingRewardsVesting.Rewards; enum LockupPeriod { SixMonths, TwelveMonths, TwentyFourMonths } struct StakedPosition { // @notice Staked amount denominated in `stakingToken().decimals()` uint256 amount; // @notice Struct describing rewards owed with vesting StakingRewardsVesting.Rewards rewards; // @notice Multiplier applied to staked amount when locking up position uint256 leverageMultiplier; // @notice Time in seconds after which position can be unstaked uint256 lockedUntil; } /* ========== EVENTS =================== */ event RewardsParametersUpdated( address indexed who, uint256 targetCapacity, uint256 minRate, uint256 maxRate, uint256 minRateAtPercent, uint256 maxRateAtPercent ); event TargetCapacityUpdated(address indexed who, uint256 targetCapacity); event VestingScheduleUpdated(address indexed who, uint256 vestingLength); event MinRateUpdated(address indexed who, uint256 minRate); event MaxRateUpdated(address indexed who, uint256 maxRate); event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent); event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent); event LeverageMultiplierUpdated(address indexed who, LockupPeriod lockupPeriod, uint256 leverageMultiplier); /* ========== STATE VARIABLES ========== */ uint256 private constant MULTIPLIER_DECIMALS = 1e18; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); GoldfinchConfig public config; /// @notice The block timestamp when rewards were last checkpointed uint256 public lastUpdateTime; /// @notice Accumulated rewards per token at the last checkpoint uint256 public accumulatedRewardsPerToken; /// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken; /// @notice Desired supply of staked tokens. The reward rate adjusts in a range /// around this value to incentivize staking or unstaking to maintain it. uint256 public targetCapacity; /// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public minRate; /// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public maxRate; /// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public maxRateAtPercent; /// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public minRateAtPercent; /// @notice The duration in seconds over which rewards vest uint256 public vestingLength; /// @dev Supply of staked tokens, excluding leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 public totalStakedSupply; /// @dev Supply of staked tokens, including leverage due to lock-up boosting, denominated in /// `stakingToken().decimals()` uint256 private totalLeveragedStakedSupply; /// @dev A mapping from lockup periods to leverage multipliers used to boost rewards. /// See `stakeWithLockup`. mapping(LockupPeriod => uint256) private leverageMultipliers; /// @dev NFT tokenId => staked position mapping(uint256 => StakedPosition) public positions; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); config = _config; vestingLength = 365 days; // Set defaults for leverage multipliers (no boosting) leverageMultipliers[LockupPeriod.SixMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwelveMonths] = MULTIPLIER_DECIMALS; // 1x leverageMultipliers[LockupPeriod.TwentyFourMonths] = MULTIPLIER_DECIMALS; // 1x } /* ========== VIEWS ========== */ /// @notice Returns the staked balance of a given position token /// @param tokenId A staking position token ID /// @return Amount of staked tokens denominated in `stakingToken().decimals()` function stakedBalanceOf(uint256 tokenId) external view returns (uint256) { return positions[tokenId].amount; } /// @notice The address of the token being disbursed as rewards function rewardsToken() public view returns (IERC20withDec) { return config.getGFI(); } /// @notice The address of the token that can be staked function stakingToken() public view returns (IERC20withDec) { return config.getFidu(); } /// @notice The additional rewards earned per token, between the provided time and the last /// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited /// by the amount of rewards that are available for distribution; if there aren't enough /// rewards in the balance of this contract, then we shouldn't be giving them out. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) { require(time >= lastUpdateTime, "Invalid end time for range"); if (totalLeveragedStakedSupply == 0) { return 0; } uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable); uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingTokenMantissa()).div( totalLeveragedStakedSupply ); // Prevent perverse, infinite-mint scenario where totalLeveragedStakedSupply is a fraction of a token. // Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number // of tokens that should have been disbursed in the elapsed time. The attacker would need to find // a way to reduce totalLeveragedStakedSupply while maintaining a staked position of >= 1. // See: https://twitter.com/Mudit__Gupta/status/1409463917290557440 if (additionalRewardsPerToken > rewardsSinceLastUpdate) { return 0; } return additionalRewardsPerToken; } /// @notice Returns accumulated rewards per token up to the current block timestamp /// @return Amount of rewards denominated in `rewardsToken().decimals()` function rewardPerToken() public view returns (uint256) { uint256 additionalRewardsPerToken = additionalRewardsPerTokenSinceLastUpdate(block.timestamp); return accumulatedRewardsPerToken.add(additionalRewardsPerToken); } /// @notice Returns rewards earned by a given position token from its last checkpoint up to the /// current block timestamp. /// @param tokenId A staking position token ID /// @return Amount of rewards denominated in `rewardsToken().decimals()` function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return leveredAmount.mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])).div( stakingTokenMantissa() ); } /// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) { return positions[tokenId].rewards.claimable(); } /// @notice Returns the rewards that will have vested for some position with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) external pure returns (uint256 rewards) { return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount); } /// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second function rewardRate() internal view returns (uint256) { // The reward rate can be thought of as a piece-wise function: // // let intervalStart = (maxRateAtPercent * targetCapacity), // intervalEnd = (minRateAtPercent * targetCapacity), // x = totalStakedSupply // in // if x < intervalStart // y = maxRate // if x > intervalEnd // y = minRate // else // y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart) // // See an example here: // solhint-disable-next-line max-line-length // https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D // // In that example: // maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100 uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 x = totalStakedSupply; // Subsequent computation would overflow if (intervalEnd <= intervalStart) { return 0; } if (x < intervalStart) { return maxRate; } if (x > intervalEnd) { return minRate; } return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart))); } function positionToLeveredAmount(StakedPosition storage position) internal view returns (uint256) { return toLeveredAmount(position.amount, position.leverageMultiplier); } function toLeveredAmount(uint256 amount, uint256 leverageMultiplier) internal pure returns (uint256) { return amount.mul(leverageMultiplier).div(MULTIPLIER_DECIMALS); } function stakingTokenMantissa() internal view returns (uint256) { return uint256(10)**stakingToken().decimals(); } /// @notice The amount of rewards currently being earned per token per second. This amount takes into /// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not. /// This function is intended for public consumption, to know the rate at which rewards are being /// earned, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function currentEarnRatePerToken() public view returns (uint256) { uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp; uint256 elapsed = time.sub(lastUpdateTime); return additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed); } /// @notice The amount of rewards currently being earned per second, for a given position. This function /// is intended for public consumption, to know the rate at which rewards are being earned /// for a given position, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) { StakedPosition storage position = positions[tokenId]; uint256 leveredAmount = positionToLeveredAmount(position); return currentEarnRatePerToken().mul(leveredAmount).div(stakingTokenMantissa()); } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an /// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` /// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake function stake(uint256 amount) external nonReentrant whenNotPaused updateReward(0) { _stakeWithLockup(msg.sender, msg.sender, amount, 0, MULTIPLIER_DECIMALS); } /// @notice Stake `stakingToken()` and lock your position for a period of time to boost your rewards. /// When you call this function, you'll receive an an NFT representing your staked position. /// You can present your NFT to `getReward` or `unstake` to claim rewards or unstake your tokens /// respectively. Rewards vest over a schedule. /// /// A locked position's rewards are boosted using a multiplier on the staked balance. For example, /// if I lock 100 tokens for a 2x multiplier, my rewards will be calculated as if I staked 200 tokens. /// This mechanism is similar to curve.fi's CRV-boosting vote-locking. Locked positions cannot be /// unstaked until after the position's lockedUntil timestamp. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake /// @param lockupPeriod The period over which to lock staked tokens function stakeWithLockup(uint256 amount, LockupPeriod lockupPeriod) external nonReentrant whenNotPaused updateReward(0) { uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); _stakeWithLockup(msg.sender, msg.sender, amount, lockedUntil, leverageMultiplier); } /// @notice Deposit to SeniorPool and stake your shares in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockedUntil = 0; uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, MULTIPLIER_DECIMALS); } function depositToSeniorPool(uint256 usdcAmount) internal returns (uint256 fiduAmount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); IERC20withDec usdc = config.getUSDC(); usdc.safeTransferFrom(msg.sender, address(this), usdcAmount); ISeniorPool seniorPool = config.getSeniorPool(); usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount); return seniorPool.deposit(usdcAmount); } /// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStake( uint256 usdcAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStake(usdcAmount); } /// @notice Deposit to the `SeniorPool` and stake your shares with a lock-up in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. /// @param lockupPeriod The period over which to lock staked tokens function depositAndStakeWithLockup(uint256 usdcAmount, LockupPeriod lockupPeriod) public nonReentrant whenNotPaused updateReward(0) { uint256 fiduAmount = depositToSeniorPool(usdcAmount); uint256 lockDuration = lockupPeriodToDuration(lockupPeriod); uint256 leverageMultiplier = getLeverageMultiplier(lockupPeriod); uint256 lockedUntil = block.timestamp.add(lockDuration); uint256 tokenId = _stakeWithLockup(address(this), msg.sender, fiduAmount, lockedUntil, leverageMultiplier); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount, lockedUntil, leverageMultiplier); } function lockupPeriodToDuration(LockupPeriod lockupPeriod) internal pure returns (uint256 lockDuration) { if (lockupPeriod == LockupPeriod.SixMonths) { return 365 days / 2; } else if (lockupPeriod == LockupPeriod.TwelveMonths) { return 365 days; } else if (lockupPeriod == LockupPeriod.TwentyFourMonths) { return 365 days * 2; } else { revert("unsupported LockupPeriod"); } } /// @notice Get the leverage multiplier used to boost rewards for a given lockup period. /// See `stakeWithLockup`. The leverage multiplier is denominated in `MULTIPLIER_DECIMALS`. function getLeverageMultiplier(LockupPeriod lockupPeriod) public view returns (uint256) { uint256 leverageMultiplier = leverageMultipliers[lockupPeriod]; require(leverageMultiplier > 0, "unsupported LockupPeriod"); return leverageMultiplier; } /// @notice Identical to `depositAndStakeWithLockup`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param lockupPeriod The period over which to lock staked tokens /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStakeWithLockup( uint256 usdcAmount, LockupPeriod lockupPeriod, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStakeWithLockup(usdcAmount, lockupPeriod); } function _stakeWithLockup( address staker, address nftRecipient, uint256 amount, uint256 lockedUntil, uint256 leverageMultiplier ) internal returns (uint256 tokenId) { require(amount > 0, "Cannot stake 0"); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); // Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available // We do this before setting the position, because we don't want `earned` to (incorrectly) account for // position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original // synthetix contract, where the modifier is called before any staking balance for that address is recorded _updateReward(tokenId); positions[tokenId] = StakedPosition({ amount: amount, rewards: StakingRewardsVesting.Rewards({ totalUnvested: 0, totalVested: 0, totalPreviouslyVested: 0, totalClaimed: 0, startTime: block.timestamp, endTime: block.timestamp.add(vestingLength) }), leverageMultiplier: leverageMultiplier, lockedUntil: lockedUntil }); _mint(nftRecipient, tokenId); uint256 leveredAmount = positionToLeveredAmount(positions[tokenId]); totalLeveragedStakedSupply = totalLeveragedStakedSupply.add(leveredAmount); totalStakedSupply = totalStakedSupply.add(amount); // Staker is address(this) when using depositAndStake or other convenience functions if (staker != address(this)) { stakingToken().safeTransferFrom(staker, address(this), amount); } emit Staked(nftRecipient, tokenId, amount, lockedUntil, leverageMultiplier); return tokenId; } /// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender. /// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards. /// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed. /// @dev This function checkpoints rewards /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be unstaked from the position function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) { _unstake(tokenId, amount); stakingToken().safeTransfer(msg.sender, amount); } function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) public nonReentrant whenNotPaused { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) internal updateReward(tokenId) returns (uint256 usdcAmountReceived, uint256 fiduUsed) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); ISeniorPool seniorPool = config.getSeniorPool(); IFidu fidu = config.getFidu(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); usdcAmountReceived = seniorPool.withdraw(usdcAmount); fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); _unstake(tokenId, fiduUsed); config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived); return (usdcAmountReceived, fiduUsed); } function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == usdcAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length); for (uint256 i = 0; i < usdcAmounts.length; i++) { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); fiduAmounts[i] = fiduAmount; } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) public nonReentrant whenNotPaused { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) internal updateReward(tokenId) returns (uint256 usdcReceivedAmount) { usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount); _unstake(tokenId, fiduAmount); config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount); return usdcReceivedAmount; } function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts) public nonReentrant whenNotPaused { require(tokenIds.length == fiduAmounts.length, "tokenIds and usdcAmounts must be the same length"); uint256 usdcReceivedAmountTotal = 0; for (uint256 i = 0; i < fiduAmounts.length; i++) { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function _unstake(uint256 tokenId, uint256 amount) internal { require(ownerOf(tokenId) == msg.sender, "access denied"); require(amount > 0, "Cannot unstake 0"); StakedPosition storage position = positions[tokenId]; uint256 prevAmount = position.amount; require(amount <= prevAmount, "cannot unstake more than staked balance"); require(block.timestamp >= position.lockedUntil, "staked funds are locked"); // By this point, leverageMultiplier should always be 1x due to the reset logic in updateReward. // But we subtract leveredAmount from totalLeveragedStakedSupply anyway, since that is technically correct. uint256 leveredAmount = toLeveredAmount(amount, position.leverageMultiplier); totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(leveredAmount); totalStakedSupply = totalStakedSupply.sub(amount); position.amount = prevAmount.sub(amount); // Slash unvested rewards uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount); position.rewards.slash(slashingPercentage); emit Unstaked(msg.sender, tokenId, amount); } /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward /// multipler will be reset to 1x. /// @dev This will also checkpoint their rewards up to the current time. // solhint-disable-next-line no-empty-blocks function kick(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) {} /// @notice Claim rewards for a given staked position /// @param tokenId A staking position token ID function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) { require(ownerOf(tokenId) == msg.sender, "access denied"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { positions[tokenId].rewards.claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /// @notice Unstake the position's full amount and claim all rewards /// @param tokenId A staking position token ID function exit(uint256 tokenId) external { unstake(tokenId, positions[tokenId].amount); getReward(tokenId); } function exitAndWithdraw(uint256 tokenId) external { unstakeAndWithdrawInFidu(tokenId, positions[tokenId].amount); getReward(tokenId); } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) public onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); } function setRewardsParameters( uint256 _targetCapacity, uint256 _minRate, uint256 _maxRate, uint256 _minRateAtPercent, uint256 _maxRateAtPercent ) public onlyAdmin updateReward(0) { require(_maxRate >= _minRate, "maxRate must be >= then minRate"); require(_maxRateAtPercent <= _minRateAtPercent, "maxRateAtPercent must be <= minRateAtPercent"); targetCapacity = _targetCapacity; minRate = _minRate; maxRate = _maxRate; minRateAtPercent = _minRateAtPercent; maxRateAtPercent = _maxRateAtPercent; emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent); } function setLeverageMultiplier(LockupPeriod lockupPeriod, uint256 leverageMultiplier) public onlyAdmin updateReward(0) { leverageMultipliers[lockupPeriod] = leverageMultiplier; emit LeverageMultiplierUpdated(msg.sender, lockupPeriod, leverageMultiplier); } function setVestingSchedule(uint256 _vestingLength) public onlyAdmin updateReward(0) { vestingLength = _vestingLength; emit VestingScheduleUpdated(msg.sender, vestingLength); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ========== MODIFIERS ========== */ modifier updateReward(uint256 tokenId) { _updateReward(tokenId); _; } function _updateReward(uint256 tokenId) internal { uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken; accumulatedRewardsPerToken = rewardPerToken(); uint256 rewardsJustDistributed = totalLeveragedStakedSupply .mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken)) .div(stakingTokenMantissa()); rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed); lastUpdateTime = block.timestamp; if (tokenId != 0) { uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId); StakedPosition storage position = positions[tokenId]; StakingRewardsVesting.Rewards storage rewards = position.rewards; rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards); rewards.checkpoint(); positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken; // If position is unlocked, reset its leverageMultiplier back to 1x uint256 lockedUntil = position.lockedUntil; uint256 leverageMultiplier = position.leverageMultiplier; uint256 amount = position.amount; if (lockedUntil > 0 && block.timestamp >= lockedUntil && leverageMultiplier > MULTIPLIER_DECIMALS) { uint256 prevLeveredAmount = toLeveredAmount(amount, leverageMultiplier); uint256 newLeveredAmount = toLeveredAmount(amount, MULTIPLIER_DECIMALS); position.leverageMultiplier = MULTIPLIER_DECIMALS; totalLeveragedStakedSupply = totalLeveragedStakedSupply.sub(prevLeveredAmount).add(newLeveredAmount); } } } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier); event DepositedAndStaked( address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount, uint256 lockedUntil, uint256 multiplier ); event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrewMultiple( address indexed user, uint256 usdcReceivedAmount, uint256[] tokenIds, uint256[] amounts ); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); event GoldfinchConfigUpdated(address indexed who, address configAddress); } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; import "../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]. */ 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /* Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20withDec is IERC20 { /** * @dev Returns the number of decimals used for the token */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ITranchedPool.sol"; abstract contract ISeniorPool { uint256 public sharePrice; uint256 public totalLoansOutstanding; uint256 public totalWritedowns; function deposit(uint256 amount) external virtual returns (uint256 depositShares); function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 depositShares); function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount); function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function invest(ITranchedPool pool) public virtual; function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256); function redeem(uint256 tokenId) public virtual; function writedown(uint256 tokenId) public virtual; function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount); function assets() public view virtual returns (uint256); function getNumShares(uint256 amount) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IGoldfinchConfig.sol"; import "./ConfigOptions.sol"; /** * @title GoldfinchConfig * @notice This contract stores mappings of useful "protocol config state", giving a central place * for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars * are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol. * Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this * is mostly to save gas costs of having each call go through a proxy) * @author Goldfinch */ contract GoldfinchConfig is BaseUpgradeablePausable { bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); mapping(uint256 => address) public addresses; mapping(uint256 => uint256) public numbers; mapping(address => bool) public goList; event AddressUpdated(address owner, uint256 index, address oldValue, address newValue); event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue); event GoListed(address indexed member); event NoListed(address indexed member); bool public valuesInitialized; function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(GO_LISTER_ROLE, owner); _setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE); } function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin { require(addresses[addressIndex] == address(0), "Address has already been initialized"); emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress); addresses[addressIndex] = newAddress; } function setNumber(uint256 index, uint256 newNumber) public onlyAdmin { emit NumberUpdated(msg.sender, index, numbers[index], newNumber); numbers[index] = newNumber; } function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve); emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve); addresses[key] = newTreasuryReserve; } function setSeniorPoolStrategy(address newStrategy) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy); emit AddressUpdated(msg.sender, key, addresses[key], newStrategy); addresses[key] = newStrategy; } function setCreditLineImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setTranchedPoolImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setBorrowerImplementation(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function setGoldfinchConfig(address newAddress) public onlyAdmin { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); emit AddressUpdated(msg.sender, key, addresses[key], newAddress); addresses[key] = newAddress; } function initializeFromOtherConfig( address _initialConfig, uint256 numbersLength, uint256 addressesLength ) public onlyAdmin { require(!valuesInitialized, "Already initialized values"); IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig); for (uint256 i = 0; i < numbersLength; i++) { setNumber(i, initialConfig.getNumber(i)); } for (uint256 i = 0; i < addressesLength; i++) { if (getAddress(i) == address(0)) { setAddress(i, initialConfig.getAddress(i)); } } valuesInitialized = true; } /** * @dev Adds a user to go-list * @param _member address to add to go-list */ function addToGoList(address _member) public onlyGoListerRole { goList[_member] = true; emit GoListed(_member); } /** * @dev removes a user from go-list * @param _member address to remove from go-list */ function removeFromGoList(address _member) public onlyGoListerRole { goList[_member] = false; emit NoListed(_member); } /** * @dev adds many users to go-list at once * @param _members addresses to ad to go-list */ function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { addToGoList(_members[i]); } } /** * @dev removes many users from go-list at once * @param _members addresses to remove from go-list */ function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole { for (uint256 i = 0; i < _members.length; i++) { removeFromGoList(_members[i]); } } /* Using custom getters in case we want to change underlying implementation later, or add checks or validations later on. */ function getAddress(uint256 index) public view returns (address) { return addresses[index]; } function getNumber(uint256 index) public view returns (uint256) { return numbers[index]; } modifier onlyGoListerRole() { require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "../../interfaces/IPool.sol"; import "../../interfaces/IFidu.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ICreditDesk.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICUSDCContract.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/IBackerRewards.sol"; import "../../interfaces/IGoldfinchFactory.sol"; import "../../interfaces/IGo.sol"; /** * @title ConfigHelper * @notice A convenience library for getting easy access to other contracts and constants within the * protocol, through the use of the GoldfinchConfig contract * @author Goldfinch */ library ConfigHelper { function getPool(GoldfinchConfig config) internal view returns (IPool) { return IPool(poolAddress(config)); } function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) { return ISeniorPool(seniorPoolAddress(config)); } function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) { return ISeniorPoolStrategy(seniorPoolStrategyAddress(config)); } function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(usdcAddress(config)); } function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) { return ICreditDesk(creditDeskAddress(config)); } function getFidu(GoldfinchConfig config) internal view returns (IFidu) { return IFidu(fiduAddress(config)); } function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) { return ICUSDCContract(cusdcContractAddress(config)); } function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) { return IPoolTokens(poolTokensAddress(config)); } function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) { return IBackerRewards(backerRewardsAddress(config)); } function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) { return IGoldfinchFactory(goldfinchFactoryAddress(config)); } function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) { return IERC20withDec(gfiAddress(config)); } function getGo(GoldfinchConfig config) internal view returns (IGo) { return IGo(goAddress(config)); } function oneInchAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.OneInch)); } function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation)); } function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder)); } function configAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig)); } function poolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Pool)); } function poolTokensAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens)); } function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards)); } function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool)); } function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy)); } function creditDeskAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk)); } function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory)); } function gfiAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.GFI)); } function fiduAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Fidu)); } function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract)); } function usdcAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.USDC)); } function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation)); } function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation)); } function reserveAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve)); } function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin)); } function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation)); } function goAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.Go)); } function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) { return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards)); } function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator)); } function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator)); } function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays)); } function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays)); } function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds)); } function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays)); } function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) { return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./PauserPausable.sol"; /** * @title BaseUpgradeablePausable contract * @notice This is our Base contract that most other contracts inherit from. It includes many standard * useful abilities like ugpradeability, pausability, access control, and re-entrancy guards. * @author Goldfinch */ contract BaseUpgradeablePausable is Initializable, AccessControlUpgradeSafe, PauserPausable, ReentrancyGuardUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); using SafeMath for uint256; // Pre-reserving a few slots in the base contract in case we need to add things in the future. // This does not actually take up gas cost or storage cost, but it does reserve the storage slots. // See OpenZeppelin's use of this pattern here: // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37 uint256[50] private __gap1; uint256[50] private __gap2; uint256[50] private __gap3; uint256[50] private __gap4; // solhint-disable-next-line func-name-mixedcase function __BaseUpgradeablePausable__init(address owner) public initializer { require(owner != address(0), "Owner cannot be the zero address"); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; library StakingRewardsVesting { using SafeMath for uint256; using StakingRewardsVesting for Rewards; uint256 internal constant PERCENTAGE_DECIMALS = 1e18; struct Rewards { uint256 totalUnvested; uint256 totalVested; uint256 totalPreviouslyVested; uint256 totalClaimed; uint256 startTime; uint256 endTime; } function claim(Rewards storage rewards, uint256 reward) internal { rewards.totalClaimed = rewards.totalClaimed.add(reward); } function claimable(Rewards storage rewards) internal view returns (uint256) { return rewards.totalVested.add(rewards.totalPreviouslyVested).sub(rewards.totalClaimed); } function currentGrant(Rewards storage rewards) internal view returns (uint256) { return rewards.totalUnvested.add(rewards.totalVested); } /// @notice Slash the vesting rewards by `percentage`. `percentage` of the unvested portion /// of the grant is forfeited. The remaining unvested portion continues to vest over the rest /// of the vesting schedule. The already vested portion continues to be claimable. /// /// A motivating example: /// /// Let's say we're 50% through vesting, with 100 tokens granted. Thus, 50 tokens are vested and 50 are unvested. /// Now let's say the grant is slashed by 90% (e.g. for StakingRewards, because the user unstaked 90% of their /// position). 45 of the unvested tokens will be forfeited. 5 of the unvested tokens and 5 of the vested tokens /// will be considered as the "new grant", which is 50% through vesting. The remaining 45 vested tokens will be /// still be claimable at any time. function slash(Rewards storage rewards, uint256 percentage) internal { require(percentage <= PERCENTAGE_DECIMALS, "slashing percentage cannot be greater than 100%"); uint256 unvestedToSlash = rewards.totalUnvested.mul(percentage).div(PERCENTAGE_DECIMALS); uint256 vestedToMove = rewards.totalVested.mul(percentage).div(PERCENTAGE_DECIMALS); rewards.totalUnvested = rewards.totalUnvested.sub(unvestedToSlash); rewards.totalVested = rewards.totalVested.sub(vestedToMove); rewards.totalPreviouslyVested = rewards.totalPreviouslyVested.add(vestedToMove); } function checkpoint(Rewards storage rewards) internal { uint256 newTotalVested = totalVestedAt(rewards.startTime, rewards.endTime, block.timestamp, rewards.currentGrant()); if (newTotalVested > rewards.totalVested) { uint256 difference = newTotalVested.sub(rewards.totalVested); rewards.totalUnvested = rewards.totalUnvested.sub(difference); rewards.totalVested = newTotalVested; } } function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) internal pure returns (uint256) { if (end <= start) { return grantedAmount; } return Math.min(grantedAmount.mul(time.sub(start)).div(end.sub(start)), grantedAmount); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; abstract contract ITranchedPool { IV2CreditLine public creditLine; uint256 public createdAt; enum Tranches { Reserved, Senior, Junior } struct TrancheInfo { uint256 id; uint256 principalDeposited; uint256 principalSharePrice; uint256 interestSharePrice; uint256 lockedUntil; } struct PoolSlice { TrancheInfo seniorTranche; TrancheInfo juniorTranche; uint256 totalInterestAccrued; uint256 principalDeployed; } struct SliceInfo { uint256 reserveFeePercent; uint256 interestAccrued; uint256 principalAccrued; } struct ApplyResult { uint256 interestRemaining; uint256 principalRemaining; uint256 reserveDeduction; uint256 oldInterestSharePrice; uint256 oldPrincipalSharePrice; } function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public virtual; function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory); function pay(uint256 amount) external virtual; function lockJuniorCapital() external virtual; function lockPool() external virtual; function initializeNextSlice(uint256 _fundableAt) external virtual; function totalJuniorDeposits() external view virtual returns (uint256); function drawdown(uint256 amount) external virtual; function setFundableAt(uint256 timestamp) external virtual; function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId); function assess() external virtual; function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual returns (uint256 tokenId); function availableToWithdraw(uint256 tokenId) external view virtual returns (uint256 interestRedeemable, uint256 principalRedeemable); function withdraw(uint256 tokenId, uint256 amount) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMax(uint256 tokenId) external virtual returns (uint256 interestWithdrawn, uint256 principalWithdrawn); function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ICreditLine.sol"; abstract contract IV2CreditLine is ICreditLine { function principal() external view virtual returns (uint256); function totalInterestAccrued() external view virtual returns (uint256); function termStartTime() external view virtual returns (uint256); function setLimit(uint256 newAmount) external virtual; function setMaxLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; function setPrincipal(uint256 _principal) external virtual; function setTotalInterestAccrued(uint256 _interestAccrued) external virtual; function drawdown(uint256 amount) external virtual; function assess() external virtual returns ( uint256, uint256, uint256 ); function initialize( address _config, address owner, address _borrower, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public virtual; function setTermEndTime(uint256 newTermEndTime) external virtual; function setNextDueTime(uint256 newNextDueTime) external virtual; function setInterestOwed(uint256 newInterestOwed) external virtual; function setPrincipalOwed(uint256 newPrincipalOwed) external virtual; function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual; function setWritedownAmount(uint256 newWritedownAmount) external virtual; function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual; function setLateFeeApr(uint256 newLateFeeApr) external virtual; function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ICreditLine { function borrower() external view returns (address); function limit() external view returns (uint256); function maxLimit() external view returns (uint256); function interestApr() external view returns (uint256); function paymentPeriodInDays() external view returns (uint256); function principalGracePeriodInDays() external view returns (uint256); function termInDays() external view returns (uint256); function lateFeeApr() external view returns (uint256); function isLate() external view returns (bool); function withinPrincipalGracePeriod() external view returns (bool); // Accounting variables function balance() external view returns (uint256); function interestOwed() external view returns (uint256); function principalOwed() external view returns (uint256); function termEndTime() external view returns (uint256); function nextDueTime() external view returns (uint256); function interestAccruedAsOf() external view returns (uint256); function lastFullPaymentTime() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchConfig { function getNumber(uint256 index) external returns (uint256); function getAddress(uint256 index) external returns (address); function setAddress(uint256 index, address newAddress) external returns (address); function setNumber(uint256 index, uint256 newNumber) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /** * @title ConfigOptions * @notice A central place for enumerating the configurable options of our GoldfinchConfig contract * @author Goldfinch */ library ConfigOptions { // NEVER EVER CHANGE THE ORDER OF THESE! // You can rename or append. But NEVER change the order. enum Numbers { TransactionLimit, TotalFundsLimit, MaxUnderwriterLimit, ReserveDenominator, WithdrawFeeDenominator, LatenessGracePeriodInDays, LatenessMaxDays, DrawdownPeriodInSeconds, TransferRestrictionPeriodInDays, LeverageRatio } enum Addresses { Pool, CreditLineImplementation, GoldfinchFactory, CreditDesk, Fidu, USDC, TreasuryReserve, ProtocolAdmin, OneInch, TrustedForwarder, CUSDCContract, GoldfinchConfig, PoolTokens, TranchedPoolImplementation, SeniorPool, SeniorPoolStrategy, MigratedTranchedPoolImplementation, BorrowerImplementation, GFI, Go, BackerRewards, StakingRewards } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; /** * @title PauserPausable * @notice Inheriting from OpenZeppelin's Pausable contract, this does small * augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract. * It is meant to be inherited. * @author Goldfinch */ contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // solhint-disable-next-line func-name-mixedcase function __PauserPausable__init() public initializer { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must have the PAUSER_ROLE. */ function pause() public onlyPauserRole { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must have the Pauser role */ function unpause() public onlyPauserRole { _unpause(); } modifier onlyPauserRole() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IPool { uint256 public sharePrice; function deposit(uint256 amount) external virtual; function withdraw(uint256 usdcAmount) external virtual; function withdrawInFidu(uint256 fiduAmount) external virtual; function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public virtual; function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool); function drawdown(address to, uint256 amount) public virtual returns (bool); function sweepToCompound() public virtual; function sweepFromCompound() public virtual; function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual; function assets() public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface IFidu is IERC20withDec { function mintTo(address to, uint256 amount) external; function burnFrom(address to, uint256 amount) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./ISeniorPool.sol"; import "./ITranchedPool.sol"; abstract contract ISeniorPoolStrategy { function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256); function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount); function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract ICreditDesk { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual; function drawdown(address creditLineAddress, uint256 amount) external virtual; function pay(address creditLineAddress, uint256 amount) external virtual; function assessCreditLine(address creditLineAddress) external virtual; function applyPayment(address creditLineAddress, uint256 amount) external virtual; function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256); } // SPDX-License-Identifier: MIT // Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IERC20withDec.sol"; interface ICUSDCContract is IERC20withDec { /*** User Interface ***/ function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, address cTokenCollateral ) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external returns (uint256); /*** Admin Functions ***/ function _addReserves(uint256 addAmount) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; interface IPoolTokens is IERC721 { event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); struct TokenInfo { address pool; uint256 tranche; uint256 principalAmount; uint256 principalRedeemed; uint256 interestRedeemed; } struct MintParams { uint256 principalAmount; uint256 tranche; } function mint(MintParams calldata params, address to) external returns (uint256); function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external; function burn(uint256 tokenId) external; function onPoolCreated(address newPool) external; function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory); function validPool(address sender) external view returns (bool); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBackerRewards { function allocateRewards(uint256 _interestPaymentAmount) external; function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IGoldfinchFactory { function createCreditLine() external returns (address); function createBorrower(address owner) external returns (address); function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256[] calldata _allowedUIDTypes ) external returns (address); function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256[] calldata _allowedUIDTypes ) external returns (address); function updateGoldfinchConfig() external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IGo { uint256 public constant ID_TYPE_0 = 0; uint256 public constant ID_TYPE_1 = 1; uint256 public constant ID_TYPE_2 = 2; uint256 public constant ID_TYPE_3 = 3; uint256 public constant ID_TYPE_4 = 4; uint256 public constant ID_TYPE_5 = 5; uint256 public constant ID_TYPE_6 = 6; uint256 public constant ID_TYPE_7 = 7; uint256 public constant ID_TYPE_8 = 8; uint256 public constant ID_TYPE_9 = 9; uint256 public constant ID_TYPE_10 = 10; /// @notice Returns the address of the UniqueIdentity contract. function uniqueIdentity() external virtual returns (address); function go(address account) public view virtual returns (bool); function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool); function goSeniorPool(address account) public view virtual returns (bool); function updateGoldfinchConfig() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../protocol/core/Pool.sol"; import "../protocol/core/Accountant.sol"; import "../protocol/core/CreditLine.sol"; import "../protocol/core/GoldfinchConfig.sol"; contract FakeV2CreditDesk is BaseUpgradeablePausable { uint256 public totalWritedowns; uint256 public totalLoansOutstanding; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentMade( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); event LimitChanged(address indexed owner, string limitType, uint256 amount); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; function initialize(address owner, GoldfinchConfig _config) public initializer { owner; _config; return; } function someBrandNewFunction() public pure returns (uint256) { return 5; } function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; /** * @title Goldfinch's Pool contract * @notice Main entry point for LP's (a.k.a. capital providers) * Handles key logic for depositing and withdrawing funds from the Pool * @author Goldfinch */ contract Pool is BaseUpgradeablePausable, IPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; uint256 public compoundBalance; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event TransferMade(address indexed from, address indexed to, uint256 amount); event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittendown(address indexed creditline, int256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; sharePrice = fiduMantissa(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); // Unlock self for infinite amount bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant { require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits uint256 depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit."); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); } /** * @notice Withdraws USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant { require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the Pool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of fidu shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant { require(fiduAmount > 0, "Must withdraw more than zero"); if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; _withdraw(usdcAmount, withdrawShares); } /** * @notice Collects `interest` USDC in interest and `principal` in principal from `from` and sends it to the Pool. * This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address * @param from The address to take the USDC from. Implicitly, the Pool * must be authorized to move USDC on behalf of `from`. * @param interest the interest amount of USDC to move to the Pool * @param principal the principal amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public override onlyCreditDesk whenNotPaused { _collectInterestAndPrincipal(from, interest, principal); } function distributeLosses(address creditlineAddress, int256 writedownDelta) external override onlyCreditDesk whenNotPaused { if (writedownDelta > 0) { uint256 delta = usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } emit PrincipalWrittendown(creditlineAddress, writedownDelta); } /** * @notice Moves `amount` USDC from `from`, to `to`. * @param from The address to take the USDC from. Implicitly, the Pool * must be authorized to move USDC on behalf of `from`. * @param to The address that the USDC should be moved to * @param amount the amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function transferFrom( address from, address to, uint256 amount ) public override onlyCreditDesk whenNotPaused returns (bool) { bool result = doUSDCTransfer(from, to, amount); require(result, "USDC Transfer failed"); emit TransferMade(from, to, amount); return result; } /** * @notice Moves `amount` USDC from the pool, to `to`. This is similar to transferFrom except we sweep any * balance we have from compound first and recognize interest. Meant to be called only by the credit desk on drawdown * @param to The address that the USDC should be moved to * @param amount the amount of USDC to move to the Pool * * Requirements: * - The caller must be the Credit Desk. Not even the owner can call this function. */ function drawdown(address to, uint256 amount) public override onlyCreditDesk whenNotPaused returns (bool) { if (compoundBalance > 0) { _sweepFromCompound(); } return transferFrom(address(this), to, amount); } function assets() public view override returns (uint256) { ICreditDesk creditDesk = config.getCreditDesk(); return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(creditDesk.totalLoansOutstanding()).sub( creditDesk.totalWritedowns() ); } function migrateToSeniorPool() external onlyAdmin { // Bring back all USDC if (compoundBalance > 0) { sweepFromCompound(); } // Pause deposits/withdrawals if (!paused()) { pause(); } // Remove special priveldges from Fidu bytes32 minterRole = keccak256("MINTER_ROLE"); bytes32 pauserRole = keccak256("PAUSER_ROLE"); config.getFidu().renounceRole(minterRole, address(this)); config.getFidu().renounceRole(pauserRole, address(this)); // Move all USDC to the SeniorPool address seniorPoolAddress = config.seniorPoolAddress(); uint256 balance = config.getUSDC().balanceOf(address(this)); bool success = doUSDCTransfer(address(this), seniorPoolAddress, balance); require(success, "Failed to transfer USDC balance to the senior pool"); // Claim our COMP! address compoundController = address(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); bytes memory data = abi.encodeWithSignature("claimComp(address)", address(this)); bytes memory _res; // solhint-disable-next-line avoid-low-level-calls (success, _res) = compoundController.call(data); require(success, "Failed to claim COMP"); // Send our balance of COMP! address compToken = address(0xc00e94Cb662C3520282E6f5717214004A7f26888); data = abi.encodeWithSignature("balanceOf(address)", address(this)); // solhint-disable-next-line avoid-low-level-calls (success, _res) = compToken.call(data); uint256 compBalance = toUint256(_res); data = abi.encodeWithSignature("transfer(address,uint256)", seniorPoolAddress, compBalance); // solhint-disable-next-line avoid-low-level-calls (success, _res) = compToken.call(data); require(success, "Failed to transfer COMP"); } function toUint256(bytes memory _bytes) internal pure returns (uint256 value) { assembly { value := mload(add(_bytes, 0x20)) } } /** * @notice Moves any USDC still in the Pool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the Pool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /* Internal Functions */ function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal withinTransactionLimit(usdcAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); uint256 userAmount = usdcAmount.sub(reserveAmount); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); // Send the amounts bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); sendToReserve(address(this), reserveAmount, msg.sender); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); } function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); _collectInterestAndPrincipal(address(this), interestAccrued, 0); compoundBalance = 0; } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 reserveAmount = interest.div(config.getReserveDenominator()); uint256 poolAmount = interest.sub(reserveAmount); uint256 increment = usdcToSharePrice(poolAmount); sharePrice = sharePrice.add(increment); if (poolAmount > 0) { emit InterestCollected(from, poolAmount, reserveAmount); } if (principal > 0) { emit PrincipalCollected(from, principal); } if (reserveAmount > 0) { sendToReserve(from, reserveAmount, from); } // Gas savings: No need to transfer to yourself, which happens in sweepFromCompound if (from != address(this)) { bool success = doUSDCTransfer(from, address(this), principal.add(poolAmount)); require(success, "Failed to collect principal repayment"); } } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(fiduMantissa()).div(usdcMantissa()); } function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares()); } function poolWithinLimit(uint256 _totalShares) internal view returns (bool) { return _totalShares.mul(sharePrice).div(fiduMantissa()) <= usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit))); } function transactionWithinLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function getNumShares(uint256 amount) internal view returns (uint256) { return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice); } function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa())); } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function sendToReserve( address from, uint256 amount, address userForEvent ) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(from, config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } modifier withinTransactionLimit(uint256 amount) { require(transactionWithinLimit(amount), "Amount is over the per-transaction limit"); _; } modifier onlyCreditDesk() { require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./CreditLine.sol"; import "../../interfaces/ICreditLine.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title The Accountant * @notice Library for handling key financial calculations, such as interest and principal accrual. * @author Goldfinch */ library Accountant { using SafeMath for uint256; using FixedPoint for FixedPoint.Signed; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for int256; using FixedPoint for uint256; // Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled uint256 public constant FP_SCALING_FACTOR = 10**18; uint256 public constant INTEREST_DECIMALS = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant SECONDS_PER_YEAR = (SECONDS_PER_DAY * 365); struct PaymentAllocation { uint256 interestPayment; uint256 principalPayment; uint256 additionalBalancePayment; } function calculateInterestAndPrincipalAccrued( CreditLine cl, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 balance = cl.balance(); // gas optimization uint256 interestAccrued = calculateInterestAccrued(cl, balance, timestamp, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, timestamp); return (interestAccrued, principalAccrued); } function calculateInterestAndPrincipalAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { uint256 interestAccrued = calculateInterestAccruedOverPeriod(cl, balance, startTime, endTime, lateFeeGracePeriod); uint256 principalAccrued = calculatePrincipalAccrued(cl, balance, endTime); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued( ICreditLine cl, uint256 balance, uint256 timestamp ) public view returns (uint256) { // If we've already accrued principal as of the term end time, then don't accrue more principal uint256 termEndTime = cl.termEndTime(); if (cl.interestAccruedAsOf() >= termEndTime) { return 0; } if (timestamp >= termEndTime) { return balance; } else { return 0; } } function calculateWritedownFor( ICreditLine cl, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { return calculateWritedownForPrincipal(cl, cl.balance(), timestamp, gracePeriodInDays, maxDaysLate); } function calculateWritedownForPrincipal( ICreditLine cl, uint256 principal, uint256 timestamp, uint256 gracePeriodInDays, uint256 maxDaysLate ) public view returns (uint256, uint256) { FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl); if (amountOwedPerDay.isEqual(0)) { return (0, 0); } FixedPoint.Unsigned memory fpGracePeriod = FixedPoint.fromUnscaledUint(gracePeriodInDays); FixedPoint.Unsigned memory daysLate; // Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30, // Before the term end date, we use the interestOwed to calculate the periods late. However, after the loan term // has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to // calculate the periods later. uint256 totalOwed = cl.interestOwed().add(cl.principalOwed()); daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay); if (timestamp > cl.termEndTime()) { uint256 secondsLate = timestamp.sub(cl.termEndTime()); daysLate = daysLate.add(FixedPoint.fromUnscaledUint(secondsLate).div(SECONDS_PER_DAY)); } FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate); FixedPoint.Unsigned memory writedownPercent; if (daysLate.isLessThanOrEqual(fpGracePeriod)) { // Within the grace period, we don't have to write down, so assume 0% writedownPercent = FixedPoint.fromUnscaledUint(0); } else { writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate)); } FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(principal).div(FP_SCALING_FACTOR); // This will return a number between 0-100 representing the write down percent with no decimals uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue; return (unscaledWritedownPercent, writedownAmount.rawValue); } function calculateAmountOwedForOneDay(ICreditLine cl) public view returns (FixedPoint.Unsigned memory interestOwed) { // Determine theoretical interestOwed for one full day uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365); return interestOwed; } function calculateInterestAccrued( CreditLine cl, uint256 balance, uint256 timestamp, uint256 lateFeeGracePeriodInDays ) public view returns (uint256) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numSecondsElapsed. Typically this shouldn't be possible, because // the interestAccruedAsOf couldn't be *after* the current timestamp. However, when assessing // we allow this function to be called with a past timestamp, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this function's purpose is just to normalize balances, and handing in a past timestamp // will necessarily return zero interest accrued (because zero elapsed time), which is correct. uint256 startTime = Math.min(timestamp, cl.interestAccruedAsOf()); return calculateInterestAccruedOverPeriod(cl, balance, startTime, timestamp, lateFeeGracePeriodInDays); } function calculateInterestAccruedOverPeriod( CreditLine cl, uint256 balance, uint256 startTime, uint256 endTime, uint256 lateFeeGracePeriodInDays ) public view returns (uint256 interestOwed) { uint256 secondsElapsed = endTime.sub(startTime); uint256 totalInterestPerYear = balance.mul(cl.interestApr()).div(INTEREST_DECIMALS); interestOwed = totalInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); if (lateFeeApplicable(cl, endTime, lateFeeGracePeriodInDays)) { uint256 lateFeeInterestPerYear = balance.mul(cl.lateFeeApr()).div(INTEREST_DECIMALS); uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(secondsElapsed).div(SECONDS_PER_YEAR); interestOwed = interestOwed.add(additionalLateFeeInterest); } return interestOwed; } function lateFeeApplicable( CreditLine cl, uint256 timestamp, uint256 gracePeriodInDays ) public view returns (bool) { uint256 secondsLate = timestamp.sub(cl.lastFullPaymentTime()); return cl.lateFeeApr() > 0 && secondsLate > gracePeriodInDays.mul(SECONDS_PER_DAY); } function allocatePayment( uint256 paymentAmount, uint256 balance, uint256 interestOwed, uint256 principalOwed ) public pure returns (PaymentAllocation memory) { uint256 paymentRemaining = paymentAmount; uint256 interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint256 principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint256 balanceRemaining = balance.sub(principalPayment); uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "./BaseUpgradeablePausable.sol"; import "./Accountant.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ICreditLine.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; /** * @title CreditLine * @notice A contract that represents the agreement between Backers and * a Borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed. * A CreditLine belongs to a TranchedPool, and is fully controlled by that TranchedPool. It does not * operate in any standalone capacity. It should generally be considered internal to the TranchedPool. * @author Goldfinch */ // solhint-disable-next-line max-states-count contract CreditLine is BaseUpgradeablePausable, ICreditLine { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; event GoldfinchConfigUpdated(address indexed who, address configAddress); // Credit line terms address public override borrower; uint256 public currentLimit; uint256 public override maxLimit; uint256 public override interestApr; uint256 public override paymentPeriodInDays; uint256 public override termInDays; uint256 public override principalGracePeriodInDays; uint256 public override lateFeeApr; // Accounting variables uint256 public override balance; uint256 public override interestOwed; uint256 public override principalOwed; uint256 public override termEndTime; uint256 public override nextDueTime; uint256 public override interestAccruedAsOf; uint256 public override lastFullPaymentTime; uint256 public totalInterestAccrued; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; function initialize( address _config, address owner, address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public initializer { require(_config != address(0) && owner != address(0) && _borrower != address(0), "Zero address passed in"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); borrower = _borrower; maxLimit = _maxLimit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; principalGracePeriodInDays = _principalGracePeriodInDays; interestAccruedAsOf = block.timestamp; // Unlock owner, which is a TranchedPool, for infinite amount bool success = config.getUSDC().approve(owner, uint256(-1)); require(success, "Failed to approve USDC"); } function limit() external view override returns (uint256) { return currentLimit; } /** * @notice Updates the internal accounting to track a drawdown as of current block timestamp. * Does not move any money * @param amount The amount in USDC that has been drawndown */ function drawdown(uint256 amount) external onlyAdmin { require(amount.add(balance) <= currentLimit, "Cannot drawdown more than the limit"); require(amount > 0, "Invalid drawdown amount"); uint256 timestamp = currentTime(); if (balance == 0) { setInterestAccruedAsOf(timestamp); setLastFullPaymentTime(timestamp); setTotalInterestAccrued(0); setTermEndTime(timestamp.add(SECONDS_PER_DAY.mul(termInDays))); } (uint256 _interestOwed, uint256 _principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); balance = balance.add(amount); updateCreditLineAccounting(balance, _interestOwed, _principalOwed); require(!_isLate(timestamp), "Cannot drawdown when payments are past due"); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin { lateFeeApr = newLateFeeApr; } function setLimit(uint256 newAmount) external onlyAdmin { require(newAmount <= maxLimit, "Cannot be more than the max limit"); currentLimit = newAmount; } function setMaxLimit(uint256 newAmount) external onlyAdmin { maxLimit = newAmount; } function termStartTime() external view returns (uint256) { return _termStartTime(); } function isLate() external view override returns (bool) { return _isLate(block.timestamp); } function withinPrincipalGracePeriod() external view override returns (bool) { if (termEndTime == 0) { // Loan hasn't started yet return true; } return block.timestamp < _termStartTime().add(principalGracePeriodInDays.mul(SECONDS_PER_DAY)); } function setTermEndTime(uint256 newTermEndTime) public onlyAdmin { termEndTime = newTermEndTime; } function setNextDueTime(uint256 newNextDueTime) public onlyAdmin { nextDueTime = newNextDueTime; } function setBalance(uint256 newBalance) public onlyAdmin { balance = newBalance; } function setTotalInterestAccrued(uint256 _totalInterestAccrued) public onlyAdmin { totalInterestAccrued = _totalInterestAccrued; } function setInterestOwed(uint256 newInterestOwed) public onlyAdmin { interestOwed = newInterestOwed; } function setPrincipalOwed(uint256 newPrincipalOwed) public onlyAdmin { principalOwed = newPrincipalOwed; } function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) public onlyAdmin { interestAccruedAsOf = newInterestAccruedAsOf; } function setLastFullPaymentTime(uint256 newLastFullPaymentTime) public onlyAdmin { lastFullPaymentTime = newLastFullPaymentTime; } /** * @notice Triggers an assessment of the creditline. Any USDC balance available in the creditline is applied * towards the interest and principal. * @return Any amount remaining after applying payments towards the interest and principal * @return Amount applied towards interest * @return Amount applied towards principal */ function assess() public onlyAdmin returns ( uint256, uint256, uint256 ) { // Do not assess until a full period has elapsed or past due require(balance > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < nextDueTime && !_isLate(currentTime())) { return (0, 0, 0); } uint256 timeToAssess = calculateNextDueTime(); setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } return handlePayment(getUSDCBalance(address(this)), timeToAssess); } function calculateNextDueTime() internal view returns (uint256) { uint256 newNextDueTime = nextDueTime; uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (newNextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* newNextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= newNextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(newNextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); newNextDueTime = newNextDueTime.add(secondsToAdvance); return Math.min(newNextDueTime, termEndTime); } // You're paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && newNextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the newNextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < newNextDueTime) { return newNextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function _isLate(uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(lastFullPaymentTime); return balance > 0 && secondsElapsedSinceFullPayment > paymentPeriodInDays.mul(SECONDS_PER_DAY); } function _termStartTime() internal view returns (uint256) { return termEndTime.sub(SECONDS_PER_DAY.mul(termInDays)); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param paymentAmount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function handlePayment(uint256 paymentAmount, uint256 timestamp) internal returns ( uint256, uint256, uint256 ) { (uint256 newInterestOwed, uint256 newPrincipalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, balance, newInterestOwed, newPrincipalOwed ); uint256 newBalance = balance.sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = balance.sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( newBalance, newInterestOwed.sub(pa.interestPayment), newPrincipalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function updateAndGetInterestAndPrincipalOwedAsOf(uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( this, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. setInterestAccruedAsOf(timestamp); totalInterestAccrued = totalInterestAccrued.add(interestAccrued); } return (interestOwed.add(interestAccrued), principalOwed.add(principalAccrued)); } function updateCreditLineAccounting( uint256 newBalance, uint256 newInterestOwed, uint256 newPrincipalOwed ) internal nonReentrant { setBalance(newBalance); setInterestOwed(newInterestOwed); setPrincipalOwed(newPrincipalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 _nextDueTime = nextDueTime; if (newInterestOwed == 0 && _nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < _nextDueTime) { uint256 secondsPerPeriod = paymentPeriodInDays.mul(SECONDS_PER_DAY); mostRecentLastDueTime = _nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = _nextDueTime; } setLastFullPaymentTime(mostRecentLastDueTime); } setNextDueTime(calculateNextDueTime()); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } } // SPDX-License-Identifier: AGPL-3.0-only // solhint-disable // Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IERC20withDec.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/TranchedPool.sol"; contract TestTranchedPool is TranchedPool { function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) public { collectInterestAndPrincipal(from, interest, principal); } function _setSeniorTranchePrincipalDeposited(uint256 principalDeposited) public { poolSlices[poolSlices.length - 1].seniorTranche.principalDeposited = principalDeposited; } function _setLimit(uint256 limit) public { creditLine.setLimit(limit); } function _modifyJuniorTrancheLockedUntil(uint256 lockedUntil) public { poolSlices[poolSlices.length - 1].juniorTranche.lockedUntil = lockedUntil; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/IV2CreditLine.sol"; import "../../interfaces/IPoolTokens.sol"; import "./GoldfinchConfig.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../library/SafeERC20Transfer.sol"; import "./TranchingLogic.sol"; contract TranchedPool is BaseUpgradeablePausable, ITranchedPool, SafeERC20Transfer { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using TranchingLogic for PoolSlice; using TranchingLogic for TrancheInfo; bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE"); bytes32 public constant SENIOR_ROLE = keccak256("SENIOR_ROLE"); uint256 public constant FP_SCALING_FACTOR = 1e18; uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100 uint256 public constant NUM_TRANCHES_PER_SLICE = 2; uint256 public juniorFeePercent; bool public drawdownsPaused; uint256[] public allowedUIDTypes; uint256 public totalDeployed; uint256 public fundableAt; PoolSlice[] public poolSlices; event DepositMade(address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 amount); event WithdrawalMade( address indexed owner, uint256 indexed tranche, uint256 indexed tokenId, uint256 interestWithdrawn, uint256 principalWithdrawn ); event GoldfinchConfigUpdated(address indexed who, address configAddress); event TranchedPoolAssessed(address indexed pool); event PaymentApplied( address indexed payer, address indexed pool, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount, uint256 reserveAmount ); // Note: This has to exactly match the even in the TranchingLogic library for events to be emitted // correctly event SharePriceUpdated( address indexed pool, uint256 indexed tranche, uint256 principalSharePrice, int256 principalDelta, uint256 interestSharePrice, int256 interestDelta ); event ReserveFundsCollected(address indexed from, uint256 amount); event CreditLineMigrated(address indexed oldCreditLine, address indexed newCreditLine); event DrawdownMade(address indexed borrower, uint256 amount); event DrawdownsPaused(address indexed pool); event DrawdownsUnpaused(address indexed pool); event EmergencyShutdown(address indexed pool); event TrancheLocked(address indexed pool, uint256 trancheId, uint256 lockedUntil); event SliceCreated(address indexed pool, uint256 sliceId); function initialize( address _config, address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) public override initializer { require(address(_config) != address(0) && address(_borrower) != address(0), "Config/borrower invalid"); config = GoldfinchConfig(_config); address owner = config.protocolAdminAddress(); require(owner != address(0), "Owner invalid"); __BaseUpgradeablePausable__init(owner); _initializeNextSlice(_fundableAt); createAndSetCreditLine( _borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); createdAt = block.timestamp; juniorFeePercent = _juniorFeePercent; if (_allowedUIDTypes.length == 0) { uint256[1] memory defaultAllowedUIDTypes = [config.getGo().ID_TYPE_0()]; allowedUIDTypes = defaultAllowedUIDTypes; } else { allowedUIDTypes = _allowedUIDTypes; } _setupRole(LOCKER_ROLE, _borrower); _setupRole(LOCKER_ROLE, owner); _setRoleAdmin(LOCKER_ROLE, OWNER_ROLE); _setRoleAdmin(SENIOR_ROLE, OWNER_ROLE); // Give the senior pool the ability to deposit into the senior pool _setupRole(SENIOR_ROLE, address(config.getSeniorPool())); // Unlock self for infinite amount bool success = config.getUSDC().approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } function setAllowedUIDTypes(uint256[] calldata ids) public onlyLocker { require( poolSlices[0].juniorTranche.principalDeposited == 0 && poolSlices[0].seniorTranche.principalDeposited == 0, "Must not have balance" ); allowedUIDTypes = ids; } /** * @notice Deposit a USDC amount into the pool for a tranche. Mints an NFT to the caller representing the position * @param tranche The number representing the tranche to deposit into * @param amount The USDC amount to tranfer from the caller to the pool * @return tokenId The tokenId of the NFT */ function deposit(uint256 tranche, uint256 amount) public override nonReentrant whenNotPaused returns (uint256 tokenId) { TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche locked"); require(amount > 0, "Must deposit > zero"); require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed"); require(block.timestamp > fundableAt, "Not open for funding"); // senior tranche ids are always odd numbered if (_isSeniorTrancheId(trancheInfo.id)) { require(hasRole(SENIOR_ROLE, _msgSender()), "Req SENIOR_ROLE"); } trancheInfo.principalDeposited = trancheInfo.principalDeposited.add(amount); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({tranche: tranche, principalAmount: amount}); tokenId = config.getPoolTokens().mint(params, msg.sender); safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); emit DepositMade(msg.sender, tranche, tokenId, amount); return tokenId; } function depositWithPermit( uint256 tranche, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 tokenId) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(tranche, amount); } /** * @notice Withdraw an already deposited amount if the funds are available * @param tokenId The NFT representing the position * @param amount The amount to withdraw (must be <= interest+principal currently available to withdraw) * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdraw(uint256 tokenId, uint256 amount) public override nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Withdraw from many tokens (that the sender owns) in a single transaction * @param tokenIds An array of tokens ids representing the position * @param amounts An array of amounts to withdraw from the corresponding tokenIds */ function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) public override { require(tokenIds.length == amounts.length, "TokensIds and Amounts mismatch"); for (uint256 i = 0; i < amounts.length; i++) { withdraw(tokenIds[i], amounts[i]); } } /** * @notice Similar to withdraw but will withdraw all available funds * @param tokenId The NFT representing the position * @return interestWithdrawn The interest amount that was withdrawn * @return principalWithdrawn The principal amount that was withdrawn */ function withdrawMax(uint256 tokenId) external override nonReentrant whenNotPaused returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 amount = interestRedeemable.add(principalRedeemable); return _withdraw(trancheInfo, tokenInfo, tokenId, amount); } /** * @notice Draws down the funds (and locks the pool) to the borrower address. Can only be called by the borrower * @param amount The amount to drawdown from the creditline (must be < limit) */ function drawdown(uint256 amount) external override onlyLocker whenNotPaused { require(!drawdownsPaused, "Drawdowns are paused"); if (!locked()) { // Assumes the senior pool has invested already (saves the borrower a separate transaction to lock the pool) _lockPool(); } // Drawdown only draws down from the current slice for simplicity. It's harder to account for how much // money is available from previous slices since depositors can redeem after unlock. PoolSlice storage currentSlice = poolSlices[poolSlices.length.sub(1)]; uint256 amountAvailable = sharePriceToUsdc( currentSlice.juniorTranche.principalSharePrice, currentSlice.juniorTranche.principalDeposited ); amountAvailable = amountAvailable.add( sharePriceToUsdc(currentSlice.seniorTranche.principalSharePrice, currentSlice.seniorTranche.principalDeposited) ); require(amount <= amountAvailable, "Insufficient funds in slice"); creditLine.drawdown(amount); // Update the share price to reflect the amount remaining in the pool uint256 amountRemaining = amountAvailable.sub(amount); uint256 oldJuniorPrincipalSharePrice = currentSlice.juniorTranche.principalSharePrice; uint256 oldSeniorPrincipalSharePrice = currentSlice.seniorTranche.principalSharePrice; currentSlice.juniorTranche.principalSharePrice = currentSlice.juniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.seniorTranche.principalSharePrice = currentSlice.seniorTranche.calculateExpectedSharePrice( amountRemaining, currentSlice ); currentSlice.principalDeployed = currentSlice.principalDeployed.add(amount); totalDeployed = totalDeployed.add(amount); address borrower = creditLine.borrower(); safeERC20TransferFrom(config.getUSDC(), address(this), borrower, amount); emit DrawdownMade(borrower, amount); emit SharePriceUpdated( address(this), currentSlice.juniorTranche.id, currentSlice.juniorTranche.principalSharePrice, int256(oldJuniorPrincipalSharePrice.sub(currentSlice.juniorTranche.principalSharePrice)) * -1, currentSlice.juniorTranche.interestSharePrice, 0 ); emit SharePriceUpdated( address(this), currentSlice.seniorTranche.id, currentSlice.seniorTranche.principalSharePrice, int256(oldSeniorPrincipalSharePrice.sub(currentSlice.seniorTranche.principalSharePrice)) * -1, currentSlice.seniorTranche.interestSharePrice, 0 ); } /** * @notice Locks the junior tranche, preventing more junior deposits. Gives time for the senior to determine how * much to invest (ensure leverage ratio cannot change for the period) */ function lockJuniorCapital() external override onlyLocker whenNotPaused { _lockJuniorCapital(poolSlices.length.sub(1)); } /** * @notice Locks the pool (locks both senior and junior tranches and starts the drawdown period). Beyond the drawdown * period, any unused capital is available to withdraw by all depositors */ function lockPool() external override onlyLocker whenNotPaused { _lockPool(); } function setFundableAt(uint256 newFundableAt) external override onlyLocker { fundableAt = newFundableAt; } function initializeNextSlice(uint256 _fundableAt) external override onlyLocker whenNotPaused { require(locked(), "Current slice still active"); require(!creditLine.isLate(), "Creditline is late"); require(creditLine.withinPrincipalGracePeriod(), "Beyond principal grace period"); _initializeNextSlice(_fundableAt); emit SliceCreated(address(this), poolSlices.length.sub(1)); } /** * @notice Triggers an assessment of the creditline and the applies the payments according the tranche waterfall */ function assess() external override whenNotPaused { _assess(); } /** * @notice Allows repaying the creditline. Collects the USDC amount from the sender and triggers an assess * @param amount The amount to repay */ function pay(uint256 amount) external override whenNotPaused { require(amount > 0, "Must pay more than zero"); collectPayment(amount); _assess(); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); creditLine.updateGoldfinchConfig(); emit GoldfinchConfigUpdated(msg.sender, address(config)); } /** * @notice Pauses the pool and sweeps any remaining funds to the treasury reserve. */ function emergencyShutdown() public onlyAdmin { if (!paused()) { pause(); } IERC20withDec usdc = config.getUSDC(); address reserveAddress = config.reserveAddress(); // Sweep any funds to community reserve uint256 poolBalance = usdc.balanceOf(address(this)); if (poolBalance > 0) { safeERC20Transfer(usdc, reserveAddress, poolBalance); } uint256 clBalance = usdc.balanceOf(address(creditLine)); if (clBalance > 0) { safeERC20TransferFrom(usdc, address(creditLine), reserveAddress, clBalance); } emit EmergencyShutdown(address(this)); } /** * @notice Pauses all drawdowns (but not deposits/withdraws) */ function pauseDrawdowns() public onlyAdmin { drawdownsPaused = true; emit DrawdownsPaused(address(this)); } /** * @notice Unpause drawdowns */ function unpauseDrawdowns() public onlyAdmin { drawdownsPaused = false; emit DrawdownsUnpaused(address(this)); } /** * @notice Migrates the accounting variables from the current creditline to a brand new one * @param _borrower The borrower address * @param _maxLimit The new max limit * @param _interestApr The new interest APR * @param _paymentPeriodInDays The new payment period in days * @param _termInDays The new term in days * @param _lateFeeApr The new late fee APR */ function migrateCreditLine( address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) public onlyAdmin { require(_borrower != address(0), "Borrower must not be empty"); require(_paymentPeriodInDays != 0, "Payment period invalid"); require(_termInDays != 0, "Term must not be empty"); address originalClAddr = address(creditLine); createAndSetCreditLine( _borrower, _maxLimit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); address newClAddr = address(creditLine); TranchingLogic.migrateAccountingVariables(originalClAddr, newClAddr); TranchingLogic.closeCreditLine(originalClAddr); address originalBorrower = IV2CreditLine(originalClAddr).borrower(); address newBorrower = IV2CreditLine(newClAddr).borrower(); // Ensure Roles if (originalBorrower != newBorrower) { revokeRole(LOCKER_ROLE, originalBorrower); grantRole(LOCKER_ROLE, newBorrower); } // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newClAddr, clBalance); } emit CreditLineMigrated(originalClAddr, newClAddr); } /** * @notice Migrates to a new creditline without copying the accounting variables */ function migrateAndSetNewCreditLine(address newCl) public onlyAdmin { require(newCl != address(0), "Creditline cannot be empty"); address originalClAddr = address(creditLine); // Transfer any funds to new CL uint256 clBalance = config.getUSDC().balanceOf(originalClAddr); if (clBalance > 0) { safeERC20TransferFrom(config.getUSDC(), originalClAddr, newCl, clBalance); } TranchingLogic.closeCreditLine(originalClAddr); // set new CL creditLine = IV2CreditLine(newCl); // sanity check that the new address is in fact a creditline creditLine.limit(); emit CreditLineMigrated(originalClAddr, address(creditLine)); } // CreditLine proxy method function setLimit(uint256 newAmount) external onlyAdmin { return creditLine.setLimit(newAmount); } function setMaxLimit(uint256 newAmount) external onlyAdmin { return creditLine.setMaxLimit(newAmount); } function getTranche(uint256 tranche) public view override returns (TrancheInfo memory) { return getTrancheInfo(tranche); } function numSlices() public view returns (uint256) { return poolSlices.length; } /** * @notice Converts USDC amounts to share price * @param amount The USDC amount to convert * @param totalShares The total shares outstanding * @return The share price of the input amount */ function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) { return TranchingLogic.usdcToSharePrice(amount, totalShares); } /** * @notice Converts share price to USDC amounts * @param sharePrice The share price to convert * @param totalShares The total shares outstanding * @return The USDC amount of the input share price */ function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) { return TranchingLogic.sharePriceToUsdc(sharePrice, totalShares); } /** * @notice Returns the total junior capital deposited * @return The total USDC amount deposited into all junior tranches */ function totalJuniorDeposits() external view override returns (uint256) { uint256 total; for (uint256 i = 0; i < poolSlices.length; i++) { total = total.add(poolSlices[i].juniorTranche.principalDeposited); } return total; } /** * @notice Determines the amount of interest and principal redeemable by a particular tokenId * @param tokenId The token representing the position * @return interestRedeemable The interest available to redeem * @return principalRedeemable The principal available to redeem */ function availableToWithdraw(uint256 tokenId) public view override returns (uint256 interestRedeemable, uint256 principalRedeemable) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); TrancheInfo storage trancheInfo = getTrancheInfo(tokenInfo.tranche); if (currentTime() > trancheInfo.lockedUntil) { return redeemableInterestAndPrincipal(trancheInfo, tokenInfo); } else { return (0, 0); } } /* Internal functions */ function _withdraw( TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo, uint256 tokenId, uint256 amount ) internal returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { require(config.getPoolTokens().isApprovedOrOwner(msg.sender, tokenId), "Not token owner"); require(config.getGo().goOnlyIdTypes(msg.sender, allowedUIDTypes), "Address not go-listed"); require(amount > 0, "Must withdraw more than zero"); (uint256 interestRedeemable, uint256 principalRedeemable) = redeemableInterestAndPrincipal(trancheInfo, tokenInfo); uint256 netRedeemable = interestRedeemable.add(principalRedeemable); require(amount <= netRedeemable, "Invalid redeem amount"); require(currentTime() > trancheInfo.lockedUntil, "Tranche is locked"); // If the tranche has not been locked, ensure the deposited amount is correct if (trancheInfo.lockedUntil == 0) { trancheInfo.principalDeposited = trancheInfo.principalDeposited.sub(amount); } uint256 interestToRedeem = Math.min(interestRedeemable, amount); uint256 principalToRedeem = Math.min(principalRedeemable, amount.sub(interestToRedeem)); config.getPoolTokens().redeem(tokenId, principalToRedeem, interestToRedeem); safeERC20TransferFrom(config.getUSDC(), address(this), msg.sender, principalToRedeem.add(interestToRedeem)); emit WithdrawalMade(msg.sender, tokenInfo.tranche, tokenId, interestToRedeem, principalToRedeem); return (interestToRedeem, principalToRedeem); } function _isSeniorTrancheId(uint256 trancheId) internal pure returns (bool) { return trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1; } function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo) internal view returns (uint256 interestRedeemable, uint256 principalRedeemable) { // This supports withdrawing before or after locking because principal share price starts at 1 // and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); // The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a // percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1. uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); } function _lockJuniorCapital(uint256 sliceId) internal { require(!locked(), "Pool already locked"); require(poolSlices[sliceId].juniorTranche.lockedUntil == 0, "Junior tranche already locked"); uint256 lockedUntil = currentTime().add(config.getDrawdownPeriodInSeconds()); poolSlices[sliceId].juniorTranche.lockedUntil = lockedUntil; emit TrancheLocked(address(this), poolSlices[sliceId].juniorTranche.id, lockedUntil); } function _lockPool() internal { uint256 sliceId = poolSlices.length.sub(1); require(poolSlices[sliceId].juniorTranche.lockedUntil > 0, "Junior tranche must be locked"); // Allow locking the pool only once; do not allow extending the lock of an // already-locked pool. Otherwise the locker could keep the pool locked // indefinitely, preventing withdrawals. require(poolSlices[sliceId].seniorTranche.lockedUntil == 0, "Lock cannot be extended"); uint256 currentTotal = poolSlices[sliceId].juniorTranche.principalDeposited.add( poolSlices[sliceId].seniorTranche.principalDeposited ); creditLine.setLimit(Math.min(creditLine.limit().add(currentTotal), creditLine.maxLimit())); // We start the drawdown period, so backers can withdraw unused capital after borrower draws down uint256 lockPeriod = config.getDrawdownPeriodInSeconds(); poolSlices[sliceId].seniorTranche.lockedUntil = currentTime().add(lockPeriod); poolSlices[sliceId].juniorTranche.lockedUntil = currentTime().add(lockPeriod); emit TrancheLocked( address(this), poolSlices[sliceId].seniorTranche.id, poolSlices[sliceId].seniorTranche.lockedUntil ); emit TrancheLocked( address(this), poolSlices[sliceId].juniorTranche.id, poolSlices[sliceId].juniorTranche.lockedUntil ); } function _initializeNextSlice(uint256 newFundableAt) internal { uint256 numSlices = poolSlices.length; require(numSlices < 5, "Cannot exceed 5 slices"); poolSlices.push( PoolSlice({ seniorTranche: TrancheInfo({ id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(1), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }), juniorTranche: TrancheInfo({ id: numSlices.mul(NUM_TRANCHES_PER_SLICE).add(2), principalSharePrice: usdcToSharePrice(1, 1), interestSharePrice: 0, principalDeposited: 0, lockedUntil: 0 }), totalInterestAccrued: 0, principalDeployed: 0 }) ); fundableAt = newFundableAt; } function collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal returns (uint256 totalReserveAmount) { safeERC20TransferFrom(config.getUSDC(), from, address(this), principal.add(interest), "Failed to collect payment"); uint256 reserveFeePercent = ONE_HUNDRED.div(config.getReserveDenominator()); // Convert the denonminator to percent ApplyResult memory result = TranchingLogic.applyToAllSeniorTranches( poolSlices, interest, principal, reserveFeePercent, totalDeployed, creditLine, juniorFeePercent ); totalReserveAmount = result.reserveDeduction.add( TranchingLogic.applyToAllJuniorTranches( poolSlices, result.interestRemaining, result.principalRemaining, reserveFeePercent, totalDeployed, creditLine ) ); sendToReserve(totalReserveAmount); return totalReserveAmount; } // If the senior tranche of the current slice is locked, then the pool is not open to any more deposits // (could throw off leverage ratio) function locked() internal view returns (bool) { return poolSlices[poolSlices.length.sub(1)].seniorTranche.lockedUntil > 0; } function createAndSetCreditLine( address _borrower, uint256 _maxLimit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays ) internal { address _creditLine = config.getGoldfinchFactory().createCreditLine(); creditLine = IV2CreditLine(_creditLine); creditLine.initialize( address(config), address(this), // Set self as the owner _borrower, _maxLimit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays ); } function getTrancheInfo(uint256 trancheId) internal view returns (TrancheInfo storage) { require(trancheId > 0 && trancheId <= poolSlices.length.mul(NUM_TRANCHES_PER_SLICE), "Unsupported tranche"); uint256 sliceId = ((trancheId.add(trancheId.mod(NUM_TRANCHES_PER_SLICE))).div(NUM_TRANCHES_PER_SLICE)).sub(1); PoolSlice storage slice = poolSlices[sliceId]; TrancheInfo storage trancheInfo = trancheId.mod(NUM_TRANCHES_PER_SLICE) == 1 ? slice.seniorTranche : slice.juniorTranche; return trancheInfo; } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function sendToReserve(uint256 amount) internal { emit ReserveFundsCollected(address(this), amount); safeERC20TransferFrom( config.getUSDC(), address(this), config.reserveAddress(), amount, "Failed to send to reserve" ); } function collectPayment(uint256 amount) internal { safeERC20TransferFrom(config.getUSDC(), msg.sender, address(creditLine), amount, "Failed to collect payment"); } function _assess() internal { // We need to make sure the pool is locked before we allocate rewards to ensure it's not // possible to game rewards by sandwiching an interest payment to an unlocked pool // It also causes issues trying to allocate payments to an empty slice (divide by zero) require(locked(), "Pool is not locked"); uint256 interestAccrued = creditLine.totalInterestAccrued(); (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = creditLine.assess(); interestAccrued = creditLine.totalInterestAccrued().sub(interestAccrued); // Split the interest accrued proportionally across slices so we know how much interest goes to each slice // We need this because the slice start at different times, so we cannot retroactively allocate the interest // linearly uint256[] memory principalPaymentsPerSlice = new uint256[](poolSlices.length); for (uint256 i = 0; i < poolSlices.length; i++) { uint256 interestForSlice = TranchingLogic.scaleByFraction( interestAccrued, poolSlices[i].principalDeployed, totalDeployed ); principalPaymentsPerSlice[i] = TranchingLogic.scaleByFraction( principalPayment, poolSlices[i].principalDeployed, totalDeployed ); poolSlices[i].totalInterestAccrued = poolSlices[i].totalInterestAccrued.add(interestForSlice); } if (interestPayment > 0 || principalPayment > 0) { uint256 reserveAmount = collectInterestAndPrincipal( address(creditLine), interestPayment, principalPayment.add(paymentRemaining) ); for (uint256 i = 0; i < poolSlices.length; i++) { poolSlices[i].principalDeployed = poolSlices[i].principalDeployed.sub(principalPaymentsPerSlice[i]); totalDeployed = totalDeployed.sub(principalPaymentsPerSlice[i]); } config.getBackerRewards().allocateRewards(interestPayment); emit PaymentApplied( creditLine.borrower(), address(this), interestPayment, principalPayment, paymentRemaining, reserveAmount ); } emit TranchedPoolAssessed(address(this)); } modifier onlyLocker() { require(hasRole(LOCKER_ROLE, msg.sender), "Must have locker role"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; /** * @title Safe ERC20 Transfer * @notice Reverts when transfer is not successful * @author Goldfinch */ abstract contract SafeERC20Transfer { function safeERC20Transfer( IERC20 erc20, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transfer(to, amount); require(success, message); } function safeERC20Transfer( IERC20 erc20, address to, uint256 amount ) internal { safeERC20Transfer(erc20, to, amount, "Failed to transfer ERC20"); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount, string memory message ) internal { require(to != address(0), "Can't send to zero address"); bool success = erc20.transferFrom(from, to, amount); require(success, message); } function safeERC20TransferFrom( IERC20 erc20, address from, address to, uint256 amount ) internal { string memory message = "Failed to transfer ERC20"; safeERC20TransferFrom(erc20, from, to, amount, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance, string memory message ) internal { bool success = erc20.approve(spender, allowance); require(success, message); } function safeERC20Approve( IERC20 erc20, address spender, uint256 allowance ) internal { string memory message = "Failed to approve ERC20"; safeERC20Approve(erc20, spender, allowance, message); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../interfaces/IV2CreditLine.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../external/FixedPoint.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title TranchingLogic * @notice Library for handling the payments waterfall * @author Goldfinch */ library TranchingLogic { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; event SharePriceUpdated( address indexed pool, uint256 indexed tranche, uint256 principalSharePrice, int256 principalDelta, uint256 interestSharePrice, int256 interestDelta ); uint256 public constant FP_SCALING_FACTOR = 1e18; uint256 public constant ONE_HUNDRED = 100; // Need this because we cannot call .div on a literal 100 function usdcToSharePrice(uint256 amount, uint256 totalShares) public pure returns (uint256) { return totalShares == 0 ? 0 : amount.mul(FP_SCALING_FACTOR).div(totalShares); } function sharePriceToUsdc(uint256 sharePrice, uint256 totalShares) public pure returns (uint256) { return sharePrice.mul(totalShares).div(FP_SCALING_FACTOR); } function redeemableInterestAndPrincipal( ITranchedPool.TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo ) public view returns (uint256 interestRedeemable, uint256 principalRedeemable) { // This supports withdrawing before or after locking because principal share price starts at 1 // and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); // The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a // percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1. uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); } function calculateExpectedSharePrice( ITranchedPool.TrancheInfo memory tranche, uint256 amount, ITranchedPool.PoolSlice memory slice ) public pure returns (uint256) { uint256 sharePrice = usdcToSharePrice(amount, tranche.principalDeposited); return scaleByPercentOwnership(tranche, sharePrice, slice); } function scaleForSlice( ITranchedPool.PoolSlice memory slice, uint256 amount, uint256 totalDeployed ) public pure returns (uint256) { return scaleByFraction(amount, slice.principalDeployed, totalDeployed); } // We need to create this struct so we don't run into a stack too deep error due to too many variables function getSliceInfo( ITranchedPool.PoolSlice memory slice, IV2CreditLine creditLine, uint256 totalDeployed, uint256 reserveFeePercent ) public view returns (ITranchedPool.SliceInfo memory) { (uint256 interestAccrued, uint256 principalAccrued) = getTotalInterestAndPrincipal( slice, creditLine, totalDeployed ); return ITranchedPool.SliceInfo({ reserveFeePercent: reserveFeePercent, interestAccrued: interestAccrued, principalAccrued: principalAccrued }); } function getTotalInterestAndPrincipal( ITranchedPool.PoolSlice memory slice, IV2CreditLine creditLine, uint256 totalDeployed ) public view returns (uint256 interestAccrued, uint256 principalAccrued) { principalAccrued = creditLine.principalOwed(); // In addition to principal actually owed, we need to account for early principal payments // If the borrower pays back 5K early on a 10K loan, the actual principal accrued should be // 5K (balance- deployed) + 0 (principal owed) principalAccrued = totalDeployed.sub(creditLine.balance()).add(principalAccrued); // Now we need to scale that correctly for the slice we're interested in principalAccrued = scaleForSlice(slice, principalAccrued, totalDeployed); // Finally, we need to account for partial drawdowns. e.g. If 20K was deposited, and only 10K was drawn down, // Then principal accrued should start at 10K (total deposited - principal deployed), not 0. This is because // share price starts at 1, and is decremented by what was drawn down. uint256 totalDeposited = slice.seniorTranche.principalDeposited.add(slice.juniorTranche.principalDeposited); principalAccrued = totalDeposited.sub(slice.principalDeployed).add(principalAccrued); return (slice.totalInterestAccrued, principalAccrued); } function scaleByFraction( uint256 amount, uint256 fraction, uint256 total ) public pure returns (uint256) { FixedPoint.Unsigned memory totalAsFixedPoint = FixedPoint.fromUnscaledUint(total); FixedPoint.Unsigned memory fractionAsFixedPoint = FixedPoint.fromUnscaledUint(fraction); return fractionAsFixedPoint.div(totalAsFixedPoint).mul(amount).div(FP_SCALING_FACTOR).rawValue; } function applyToAllSeniorTranches( ITranchedPool.PoolSlice[] storage poolSlices, uint256 interest, uint256 principal, uint256 reserveFeePercent, uint256 totalDeployed, IV2CreditLine creditLine, uint256 juniorFeePercent ) public returns (ITranchedPool.ApplyResult memory) { ITranchedPool.ApplyResult memory seniorApplyResult; for (uint256 i = 0; i < poolSlices.length; i++) { ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo( poolSlices[i], creditLine, totalDeployed, reserveFeePercent ); // Since slices cannot be created when the loan is late, all interest collected can be assumed to split // pro-rata across the slices. So we scale the interest and principal to the slice ITranchedPool.ApplyResult memory applyResult = applyToSeniorTranche( poolSlices[i], scaleForSlice(poolSlices[i], interest, totalDeployed), scaleForSlice(poolSlices[i], principal, totalDeployed), juniorFeePercent, sliceInfo ); emitSharePriceUpdatedEvent(poolSlices[i].seniorTranche, applyResult); seniorApplyResult.interestRemaining = seniorApplyResult.interestRemaining.add(applyResult.interestRemaining); seniorApplyResult.principalRemaining = seniorApplyResult.principalRemaining.add(applyResult.principalRemaining); seniorApplyResult.reserveDeduction = seniorApplyResult.reserveDeduction.add(applyResult.reserveDeduction); } return seniorApplyResult; } function applyToAllJuniorTranches( ITranchedPool.PoolSlice[] storage poolSlices, uint256 interest, uint256 principal, uint256 reserveFeePercent, uint256 totalDeployed, IV2CreditLine creditLine ) public returns (uint256 totalReserveAmount) { for (uint256 i = 0; i < poolSlices.length; i++) { ITranchedPool.SliceInfo memory sliceInfo = getSliceInfo( poolSlices[i], creditLine, totalDeployed, reserveFeePercent ); // Any remaining interest and principal is then shared pro-rata with the junior slices ITranchedPool.ApplyResult memory applyResult = applyToJuniorTranche( poolSlices[i], scaleForSlice(poolSlices[i], interest, totalDeployed), scaleForSlice(poolSlices[i], principal, totalDeployed), sliceInfo ); emitSharePriceUpdatedEvent(poolSlices[i].juniorTranche, applyResult); totalReserveAmount = totalReserveAmount.add(applyResult.reserveDeduction); } return totalReserveAmount; } function emitSharePriceUpdatedEvent( ITranchedPool.TrancheInfo memory tranche, ITranchedPool.ApplyResult memory applyResult ) internal { emit SharePriceUpdated( address(this), tranche.id, tranche.principalSharePrice, int256(tranche.principalSharePrice.sub(applyResult.oldPrincipalSharePrice)), tranche.interestSharePrice, int256(tranche.interestSharePrice.sub(applyResult.oldInterestSharePrice)) ); } function applyToSeniorTranche( ITranchedPool.PoolSlice storage slice, uint256 interestRemaining, uint256 principalRemaining, uint256 juniorFeePercent, ITranchedPool.SliceInfo memory sliceInfo ) public returns (ITranchedPool.ApplyResult memory) { // First determine the expected share price for the senior tranche. This is the gross amount the senior // tranche should receive. uint256 expectedInterestSharePrice = calculateExpectedSharePrice( slice.seniorTranche, sliceInfo.interestAccrued, slice ); uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice( slice.seniorTranche, sliceInfo.principalAccrued, slice ); // Deduct the junior fee and the protocol reserve uint256 desiredNetInterestSharePrice = scaleByFraction( expectedInterestSharePrice, ONE_HUNDRED.sub(juniorFeePercent.add(sliceInfo.reserveFeePercent)), ONE_HUNDRED ); // Collect protocol fee interest received (we've subtracted this from the senior portion above) uint256 reserveDeduction = scaleByFraction(interestRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED); interestRemaining = interestRemaining.sub(reserveDeduction); uint256 oldInterestSharePrice = slice.seniorTranche.interestSharePrice; uint256 oldPrincipalSharePrice = slice.seniorTranche.principalSharePrice; // Apply the interest remaining so we get up to the netInterestSharePrice (interestRemaining, principalRemaining) = applyBySharePrice( slice.seniorTranche, interestRemaining, principalRemaining, desiredNetInterestSharePrice, expectedPrincipalSharePrice ); return ITranchedPool.ApplyResult({ interestRemaining: interestRemaining, principalRemaining: principalRemaining, reserveDeduction: reserveDeduction, oldInterestSharePrice: oldInterestSharePrice, oldPrincipalSharePrice: oldPrincipalSharePrice }); } function applyToJuniorTranche( ITranchedPool.PoolSlice storage slice, uint256 interestRemaining, uint256 principalRemaining, ITranchedPool.SliceInfo memory sliceInfo ) public returns (ITranchedPool.ApplyResult memory) { // Then fill up the junior tranche with all the interest remaining, upto the principal share price uint256 expectedInterestSharePrice = slice.juniorTranche.interestSharePrice.add( usdcToSharePrice(interestRemaining, slice.juniorTranche.principalDeposited) ); uint256 expectedPrincipalSharePrice = calculateExpectedSharePrice( slice.juniorTranche, sliceInfo.principalAccrued, slice ); uint256 oldInterestSharePrice = slice.juniorTranche.interestSharePrice; uint256 oldPrincipalSharePrice = slice.juniorTranche.principalSharePrice; (interestRemaining, principalRemaining) = applyBySharePrice( slice.juniorTranche, interestRemaining, principalRemaining, expectedInterestSharePrice, expectedPrincipalSharePrice ); // All remaining interest and principal is applied towards the junior tranche as interest interestRemaining = interestRemaining.add(principalRemaining); // Since any principal remaining is treated as interest (there is "extra" interest to be distributed) // we need to make sure to collect the protocol fee on the additional interest (we only deducted the // fee on the original interest portion) uint256 reserveDeduction = scaleByFraction(principalRemaining, sliceInfo.reserveFeePercent, ONE_HUNDRED); interestRemaining = interestRemaining.sub(reserveDeduction); principalRemaining = 0; (interestRemaining, principalRemaining) = applyByAmount( slice.juniorTranche, interestRemaining.add(principalRemaining), 0, interestRemaining.add(principalRemaining), 0 ); return ITranchedPool.ApplyResult({ interestRemaining: interestRemaining, principalRemaining: principalRemaining, reserveDeduction: reserveDeduction, oldInterestSharePrice: oldInterestSharePrice, oldPrincipalSharePrice: oldPrincipalSharePrice }); } function applyBySharePrice( ITranchedPool.TrancheInfo storage tranche, uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestSharePrice, uint256 desiredPrincipalSharePrice ) public returns (uint256, uint256) { uint256 desiredInterestAmount = desiredAmountFromSharePrice( desiredInterestSharePrice, tranche.interestSharePrice, tranche.principalDeposited ); uint256 desiredPrincipalAmount = desiredAmountFromSharePrice( desiredPrincipalSharePrice, tranche.principalSharePrice, tranche.principalDeposited ); return applyByAmount(tranche, interestRemaining, principalRemaining, desiredInterestAmount, desiredPrincipalAmount); } function applyByAmount( ITranchedPool.TrancheInfo storage tranche, uint256 interestRemaining, uint256 principalRemaining, uint256 desiredInterestAmount, uint256 desiredPrincipalAmount ) public returns (uint256, uint256) { uint256 totalShares = tranche.principalDeposited; uint256 newSharePrice; (interestRemaining, newSharePrice) = applyToSharePrice( interestRemaining, tranche.interestSharePrice, desiredInterestAmount, totalShares ); tranche.interestSharePrice = newSharePrice; (principalRemaining, newSharePrice) = applyToSharePrice( principalRemaining, tranche.principalSharePrice, desiredPrincipalAmount, totalShares ); tranche.principalSharePrice = newSharePrice; return (interestRemaining, principalRemaining); } function migrateAccountingVariables(address originalClAddr, address newClAddr) public { IV2CreditLine originalCl = IV2CreditLine(originalClAddr); IV2CreditLine newCl = IV2CreditLine(newClAddr); // Copy over all accounting variables newCl.setBalance(originalCl.balance()); newCl.setLimit(originalCl.limit()); newCl.setInterestOwed(originalCl.interestOwed()); newCl.setPrincipalOwed(originalCl.principalOwed()); newCl.setTermEndTime(originalCl.termEndTime()); newCl.setNextDueTime(originalCl.nextDueTime()); newCl.setInterestAccruedAsOf(originalCl.interestAccruedAsOf()); newCl.setLastFullPaymentTime(originalCl.lastFullPaymentTime()); newCl.setTotalInterestAccrued(originalCl.totalInterestAccrued()); } function closeCreditLine(address originalCl) public { // Close out old CL IV2CreditLine oldCreditLine = IV2CreditLine(originalCl); oldCreditLine.setBalance(0); oldCreditLine.setLimit(0); oldCreditLine.setMaxLimit(0); } function desiredAmountFromSharePrice( uint256 desiredSharePrice, uint256 actualSharePrice, uint256 totalShares ) public pure returns (uint256) { // If the desired share price is lower, then ignore it, and leave it unchanged if (desiredSharePrice < actualSharePrice) { desiredSharePrice = actualSharePrice; } uint256 sharePriceDifference = desiredSharePrice.sub(actualSharePrice); return sharePriceToUsdc(sharePriceDifference, totalShares); } function applyToSharePrice( uint256 amountRemaining, uint256 currentSharePrice, uint256 desiredAmount, uint256 totalShares ) public pure returns (uint256, uint256) { // If no money left to apply, or don't need any changes, return the original amounts if (amountRemaining == 0 || desiredAmount == 0) { return (amountRemaining, currentSharePrice); } if (amountRemaining < desiredAmount) { // We don't have enough money to adjust share price to the desired level. So just use whatever amount is left desiredAmount = amountRemaining; } uint256 sharePriceDifference = usdcToSharePrice(desiredAmount, totalShares); return (amountRemaining.sub(desiredAmount), currentSharePrice.add(sharePriceDifference)); } function scaleByPercentOwnership( ITranchedPool.TrancheInfo memory tranche, uint256 amount, ITranchedPool.PoolSlice memory slice ) public pure returns (uint256) { uint256 totalDeposited = slice.juniorTranche.principalDeposited.add(slice.seniorTranche.principalDeposited); return scaleByFraction(amount, tranche.principalDeposited, totalDeposited); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol. pragma solidity 0.6.12; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/IMerkleDirectDistributor.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; contract MerkleDirectDistributor is IMerkleDirectDistributor, BaseUpgradeablePausable { using SafeERC20 for IERC20withDec; address public override gfi; bytes32 public override merkleRoot; // @dev This is a packed array of booleans. mapping(uint256 => uint256) private acceptedBitMap; function initialize( address owner, address _gfi, bytes32 _merkleRoot ) public initializer { require(owner != address(0), "Owner address cannot be empty"); require(_gfi != address(0), "GFI address cannot be empty"); require(_merkleRoot != 0, "Invalid Merkle root"); __BaseUpgradeablePausable__init(owner); gfi = _gfi; merkleRoot = _merkleRoot; } function isGrantAccepted(uint256 index) public view override returns (bool) { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; uint256 acceptedWord = acceptedBitMap[acceptedWordIndex]; uint256 mask = (1 << acceptedBitIndex); return acceptedWord & mask == mask; } function _setGrantAccepted(uint256 index) private { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex); } function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external override whenNotPaused { require(!isGrantAccepted(index), "Grant already accepted"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it accepted and perform the granting. _setGrantAccepted(index); IERC20withDec(gfi).safeTransfer(msg.sender, amount); emit GrantAccepted(index, msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ 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) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. pragma solidity 0.6.12; /// @notice Enables the transfer of GFI rewards (referred to as a "grant"), if the grant details exist in this /// contract's Merkle root. interface IMerkleDirectDistributor { /// @notice Returns the address of the GFI contract that is the token distributed as rewards by /// this contract. function gfi() external view returns (address); /// @notice Returns the merkle root of the merkle tree containing grant details available to accept. function merkleRoot() external view returns (bytes32); /// @notice Returns true if the index has been marked accepted. function isGrantAccepted(uint256 index) external view returns (bool); /// @notice Causes the sender to accept the grant consisting of the given details. Reverts if /// the inputs (which includes who the sender is) are invalid. function acceptGrant( uint256 index, uint256 amount, bytes32[] calldata merkleProof ) external; /// @notice This event is triggered whenever a call to #acceptGrant succeeds. event GrantAccepted(uint256 indexed index, address indexed account, uint256 amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../protocol/core/CreditLine.sol"; contract TestCreditLine is CreditLine {} // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Accountant.sol"; import "../protocol/core/CreditLine.sol"; contract TestAccountant { function calculateInterestAndPrincipalAccrued( address creditLineAddress, uint256 timestamp, uint256 lateFeeGracePeriod ) public view returns (uint256, uint256) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateInterestAndPrincipalAccrued(cl, timestamp, lateFeeGracePeriod); } function calculateWritedownFor( address creditLineAddress, uint256 blockNumber, uint256 gracePeriod, uint256 maxLatePeriods ) public view returns (uint256, uint256) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods); } function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) { CreditLine cl = CreditLine(creditLineAddress); return Accountant.calculateAmountOwedForOneDay(cl); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "./Accountant.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; /** * @title Goldfinch's SeniorPool contract * @notice Main entry point for senior LPs (a.k.a. capital providers) * Automatically invests across borrower pools using an adjustable strategy. * @author Goldfinch */ contract SeniorPool is BaseUpgradeablePausable, ISeniorPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; uint256 public compoundBalance; mapping(ITranchedPool => uint256) public writedowns; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event InterestCollected(address indexed payer, uint256 amount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittenDown(address indexed tranchedPool, int256 amount); event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount); event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; // Initialize sharePrice to be identical to the legacy pool. This is in the initializer // because it must only ever happen once. sharePrice = config.getPool().sharePrice(); totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding(); totalWritedowns = config.getCreditDesk().totalWritedowns(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the * equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); require(sharesWithinLimit(potentialNewTotalShares), "Deposit would put the senior pool over the total limit."); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); return depositShares; } /** * @notice Identical to deposit, except it allows for a passed up signature to permit * the Senior Pool to move funds on behalf of the user, all within one transaction. * @param amount The amount of USDC to deposit * @param v secp256k1 signature component * @param r secp256k1 signature component * @param s secp256k1 signature component */ function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 depositShares) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(amount); } /** * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); return _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(fiduAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; return _withdraw(usdcAmount, withdrawShares); } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } /** * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /** * @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy * @param pool An ITranchedPool whose senior tranche should be considered for investment */ function invest(ITranchedPool pool) public override whenNotPaused nonReentrant { require(validPool(pool), "Pool must be valid"); if (compoundBalance > 0) { _sweepFromCompound(); } ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); uint256 amount = strategy.invest(this, pool); require(amount > 0, "Investment amount must be positive"); approvePool(pool, amount); pool.deposit(uint256(ITranchedPool.Tranches.Senior), amount); emit InvestmentMadeInSenior(address(pool), amount); totalLoansOutstanding = totalLoansOutstanding.add(amount); } function estimateInvestment(ITranchedPool pool) public view override returns (uint256) { require(validPool(pool), "Pool must be valid"); ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); return strategy.estimateInvestment(this, pool); } /** * @notice Redeem interest and/or principal from an ITranchedPool investment * @param tokenId the ID of an IPoolTokens token to be redeemed */ function redeem(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId); _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed); } /** * @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price * down if we're considering the investment a loss, or up if the borrower has subsequently * made repayments that restore confidence that the full loan will be repaid. * @param tokenId the ID of an IPoolTokens token to be considered for writedown */ function writedown(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down"); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); require(validPool(pool), "Pool must be valid"); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); uint256 prevWritedownAmount = writedowns[pool]; if (writedownPercent == 0 && prevWritedownAmount == 0) { return; } int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount); writedowns[pool] = writedownAmount; distributeLosses(writedownDelta); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } emit PrincipalWrittenDown(address(pool), writedownDelta); } /** * @notice Calculates the writedown amount for a particular pool position * @param tokenId The token reprsenting the position * @return The amount in dollars the principal should be written down by */ function calculateWritedown(uint256 tokenId) public view override returns (uint256) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); return writedownAmount; } /** * @notice Returns the net assests controlled by and owed to the pool */ function assets() public view override returns (uint256) { return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns); } /** * @notice Converts and USDC amount to FIDU amount * @param amount USDC amount to convert to FIDU */ function getNumShares(uint256 amount) public view override returns (uint256) { return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice); } /* Internal Functions */ function _calculateWritedown(ITranchedPool pool, uint256 principal) internal view returns (uint256 writedownPercent, uint256 writedownAmount) { return Accountant.calculateWritedownForPrincipal( pool.creditLine(), principal, currentTime(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function distributeLosses(int256 writedownDelta) internal { if (writedownDelta > 0) { uint256 delta = usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(fiduMantissa()).div(usdcMantissa()); } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return fiduToUSDC(fiduAmount.mul(sharePrice).div(fiduMantissa())); } function sharesWithinLimit(uint256 _totalShares) internal view returns (bool) { return _totalShares.mul(sharePrice).div(fiduMantissa()) <= usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit))); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); uint256 reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); userAmount = usdcAmount.sub(reserveAmount); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); // Send the amounts bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); sendToReserve(reserveAmount, msg.sender); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); return userAmount; } function sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator()); uint256 poolAmount = interestAccrued.sub(reserveAmount); _collectInterestAndPrincipal(address(this), poolAmount, 0); if (reserveAmount > 0) { sendToReserve(reserveAmount, address(cUSDC)); } compoundBalance = 0; } function cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 increment = usdcToSharePrice(interest); sharePrice = sharePrice.add(increment); if (interest > 0) { emit InterestCollected(from, interest); } if (principal > 0) { emit PrincipalCollected(from, principal); totalLoansOutstanding = totalLoansOutstanding.sub(principal); } } function sendToReserve(uint256 amount, address userForEvent) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares()); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function validPool(ITranchedPool pool) internal view returns (bool) { return config.getPoolTokens().validPool(address(pool)); } function approvePool(ITranchedPool pool, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); bool success = usdc.approve(address(pool), allowance); require(success, "Failed to approve USDC"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/SeniorPool.sol"; contract TestSeniorPool is SeniorPool { function _getNumShares(uint256 amount) public view returns (uint256) { return getNumShares(amount); } function _usdcMantissa() public pure returns (uint256) { return usdcMantissa(); } function _fiduMantissa() public pure returns (uint256) { return fiduMantissa(); } function _usdcToFidu(uint256 amount) public pure returns (uint256) { return usdcToFidu(amount); } function _setSharePrice(uint256 newSharePrice) public returns (uint256) { sharePrice = newSharePrice; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ICommunityRewards.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../library/CommunityRewardsVesting.sol"; contract CommunityRewards is ICommunityRewards, ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using ConfigHelper for GoldfinchConfig; using CommunityRewardsVesting for CommunityRewardsVesting.Rewards; /* ========== EVENTS ========== */ event GoldfinchConfigUpdated(address indexed who, address configAddress); /* ========== STATE VARIABLES ========== */ bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE"); GoldfinchConfig public config; /// @notice Total rewards available for granting, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice Token launch time in seconds. This is used in vesting. uint256 public tokenLaunchTimeInSeconds; /// @dev NFT tokenId => rewards grant mapping(uint256 => CommunityRewardsVesting.Rewards) public grants; // solhint-disable-next-line func-name-mixedcase function __initialize__( address owner, GoldfinchConfig _config, uint256 _tokenLaunchTimeInSeconds ) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 Community Rewards Tokens", "GFI-V2-CR"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(DISTRIBUTOR_ROLE, owner); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(DISTRIBUTOR_ROLE, OWNER_ROLE); tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds; config = _config; } /* ========== VIEWS ========== */ /// @notice The token being disbursed as rewards function rewardsToken() public view override returns (IERC20withDec) { return config.getGFI(); } /// @notice Returns the rewards claimable by a given grant token, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view override returns (uint256 rewards) { return grants[tokenId].claimable(); } /// @notice Returns the rewards that will have vested for some grant with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) external pure override returns (uint256 rewards) { return CommunityRewardsVesting.getTotalVestedAt(start, end, granted, cliffLength, vestingInterval, revokedAt, time); } /* ========== MUTATIVE, ADMIN-ONLY FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) external override onlyAdmin { require(rewards > 0, "Cannot load 0 rewards"); rewardsAvailable = rewardsAvailable.add(rewards); rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); emit RewardAdded(rewards); } /// @notice Revokes rewards that have not yet vested, for a grant. The unvested rewards are /// now considered available for allocation in another grant. /// @param tokenId The tokenId corresponding to the grant whose unvested rewards to revoke. function revokeGrant(uint256 tokenId) external override whenNotPaused onlyAdmin { CommunityRewardsVesting.Rewards storage grant = grants[tokenId]; require(grant.totalGranted > 0, "Grant not defined for token id"); require(grant.revokedAt == 0, "Grant has already been revoked"); uint256 totalUnvested = grant.totalUnvestedAt(block.timestamp); require(totalUnvested > 0, "Grant has fully vested"); rewardsAvailable = rewardsAvailable.add(totalUnvested); grant.revokedAt = block.timestamp; emit GrantRevoked(tokenId, totalUnvested); } function setTokenLaunchTimeInSeconds(uint256 _tokenLaunchTimeInSeconds) external onlyAdmin { tokenLaunchTimeInSeconds = _tokenLaunchTimeInSeconds; } /// @notice updates current config function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ========== MUTATIVE, NON-ADMIN-ONLY FUNCTIONS ========== */ /// @notice Grant rewards to a recipient. The recipient address receives an /// an NFT representing their rewards grant. They can present the NFT to `getReward()` /// to claim their rewards. Rewards vest over a schedule. /// @param recipient The recipient of the grant. /// @param amount The amount of `rewardsToken()` to grant. /// @param vestingLength The duration (in seconds) over which the grant vests. /// @param cliffLength The duration (in seconds) from the start of the grant, before which has elapsed /// the vested amount remains 0. /// @param vestingInterval The interval (in seconds) at which vesting occurs. Must be a factor of `vestingLength`. function grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) external override nonReentrant whenNotPaused onlyDistributor returns (uint256 tokenId) { return _grant(recipient, amount, vestingLength, cliffLength, vestingInterval); } function _grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) internal returns (uint256 tokenId) { require(amount > 0, "Cannot grant 0 amount"); require(cliffLength <= vestingLength, "Cliff length cannot exceed vesting length"); require(vestingLength.mod(vestingInterval) == 0, "Vesting interval must be a factor of vesting length"); require(amount <= rewardsAvailable, "Cannot grant amount due to insufficient funds"); rewardsAvailable = rewardsAvailable.sub(amount); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); grants[tokenId] = CommunityRewardsVesting.Rewards({ totalGranted: amount, totalClaimed: 0, startTime: tokenLaunchTimeInSeconds, endTime: tokenLaunchTimeInSeconds.add(vestingLength), cliffLength: cliffLength, vestingInterval: vestingInterval, revokedAt: 0 }); _mint(recipient, tokenId); emit Granted(recipient, tokenId, amount, vestingLength, cliffLength, vestingInterval); return tokenId; } /// @notice Claim rewards for a given grant /// @param tokenId A grant token ID function getReward(uint256 tokenId) external override nonReentrant whenNotPaused { require(ownerOf(tokenId) == msg.sender, "access denied"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { grants[tokenId].claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /* ========== MODIFIERS ========== */ function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } function isDistributor() public view returns (bool) { return hasRole(DISTRIBUTOR_ROLE, _msgSender()); } modifier onlyDistributor() { require(isDistributor(), "Must have distributor role to perform this action"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol"; import "../interfaces/IERC20withDec.sol"; interface ICommunityRewards is IERC721 { function rewardsToken() external view returns (IERC20withDec); function claimableRewards(uint256 tokenId) external view returns (uint256 rewards); function totalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) external pure returns (uint256 rewards); function grant( address recipient, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ) external returns (uint256 tokenId); function loadRewards(uint256 rewards) external; function revokeGrant(uint256 tokenId) external; function getReward(uint256 tokenId) external; event RewardAdded(uint256 reward); event Granted( address indexed user, uint256 indexed tokenId, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ); event GrantRevoked(uint256 indexed tokenId, uint256 totalUnvested); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; library CommunityRewardsVesting { using SafeMath for uint256; using CommunityRewardsVesting for Rewards; /// @dev All time values in the Rewards struct (i.e. `startTime`, `endTime`, /// `cliffLength`, `vestingInterval`, `revokedAt`) use the same units: seconds. All timestamp /// values (i.e. `startTime`, `endTime`, `revokedAt`) are seconds since the unix epoch. /// @dev `cliffLength` is the duration from the start of the grant, before which has elapsed /// the vested amount remains 0. /// @dev `vestingInterval` is the interval at which vesting occurs. For rewards to have /// vested fully only at `endTime`, `vestingInterval` must be a factor of /// `endTime.sub(startTime)`. If `vestingInterval` is not thusly a factor, the calculation /// of `totalVestedAt()` would calculate rewards to have fully vested as of the time of the /// last whole `vestingInterval`'s elapsing before `endTime`. struct Rewards { uint256 totalGranted; uint256 totalClaimed; uint256 startTime; uint256 endTime; uint256 cliffLength; uint256 vestingInterval; uint256 revokedAt; } function claim(Rewards storage rewards, uint256 reward) internal { rewards.totalClaimed = rewards.totalClaimed.add(reward); } function claimable(Rewards storage rewards) internal view returns (uint256) { return claimable(rewards, block.timestamp); } function claimable(Rewards storage rewards, uint256 time) internal view returns (uint256) { return rewards.totalVestedAt(time).sub(rewards.totalClaimed); } function totalUnvestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) { return rewards.totalGranted.sub(rewards.totalVestedAt(time)); } function totalVestedAt(Rewards storage rewards, uint256 time) internal view returns (uint256) { return getTotalVestedAt( rewards.startTime, rewards.endTime, rewards.totalGranted, rewards.cliffLength, rewards.vestingInterval, rewards.revokedAt, time ); } function getTotalVestedAt( uint256 start, uint256 end, uint256 granted, uint256 cliffLength, uint256 vestingInterval, uint256 revokedAt, uint256 time ) internal pure returns (uint256) { if (time < start.add(cliffLength)) { return 0; } if (end <= start) { return granted; } uint256 elapsedVestingTimestamp = revokedAt > 0 ? Math.min(revokedAt, time) : time; uint256 elapsedVestingUnits = (elapsedVestingTimestamp.sub(start)).div(vestingInterval); uint256 totalVestingUnits = (end.sub(start)).div(vestingInterval); return Math.min(granted.mul(elapsedVestingUnits).div(totalVestingUnits), granted); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/MerkleDistributor.sol. pragma solidity 0.6.12; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/ICommunityRewards.sol"; import "../interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor { address public immutable override communityRewards; bytes32 public immutable override merkleRoot; // @dev This is a packed array of booleans. mapping(uint256 => uint256) private acceptedBitMap; constructor(address communityRewards_, bytes32 merkleRoot_) public { require(communityRewards_ != address(0), "Cannot use the null address"); require(merkleRoot_ != 0, "Invalid merkle root provided"); communityRewards = communityRewards_; merkleRoot = merkleRoot_; } function isGrantAccepted(uint256 index) public view override returns (bool) { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; uint256 acceptedWord = acceptedBitMap[acceptedWordIndex]; uint256 mask = (1 << acceptedBitIndex); return acceptedWord & mask == mask; } function _setGrantAccepted(uint256 index) private { uint256 acceptedWordIndex = index / 256; uint256 acceptedBitIndex = index % 256; acceptedBitMap[acceptedWordIndex] = acceptedBitMap[acceptedWordIndex] | (1 << acceptedBitIndex); } function acceptGrant( uint256 index, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval, bytes32[] calldata merkleProof ) external override { require(!isGrantAccepted(index), "Grant already accepted"); // Verify the merkle proof. // /// @dev Per the Warning in /// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#non-standard-packed-mode, /// it is important that no more than one of the arguments to `abi.encodePacked()` here be a /// dynamic type (see definition in /// https://github.com/ethereum/solidity/blob/v0.6.12/docs/abi-spec.rst#formal-specification-of-the-encoding). bytes32 node = keccak256(abi.encodePacked(index, msg.sender, amount, vestingLength, cliffLength, vestingInterval)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "Invalid proof"); // Mark it accepted and perform the granting. _setGrantAccepted(index); uint256 tokenId = ICommunityRewards(communityRewards).grant( msg.sender, amount, vestingLength, cliffLength, vestingInterval ); emit GrantAccepted(tokenId, index, msg.sender, amount, vestingLength, cliffLength, vestingInterval); } } // SPDX-License-Identifier: GPL-3.0-only // solhint-disable-next-line max-line-length // Adapted from https://github.com/Uniswap/merkle-distributor/blob/c3255bfa2b684594ecd562cacd7664b0f18330bf/contracts/interfaces/IMerkleDistributor.sol. pragma solidity 0.6.12; /// @notice Enables the granting of a CommunityRewards grant, if the grant details exist in this /// contract's Merkle root. interface IMerkleDistributor { /// @notice Returns the address of the CommunityRewards contract whose grants are distributed by this contract. function communityRewards() external view returns (address); /// @notice Returns the merkle root of the merkle tree containing grant details available to accept. function merkleRoot() external view returns (bytes32); /// @notice Returns true if the index has been marked accepted. function isGrantAccepted(uint256 index) external view returns (bool); /// @notice Causes the sender to accept the grant consisting of the given details. Reverts if /// the inputs (which includes who the sender is) are invalid. function acceptGrant( uint256 index, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval, bytes32[] calldata merkleProof ) external; /// @notice This event is triggered whenever a call to #acceptGrant succeeds. event GrantAccepted( uint256 indexed tokenId, uint256 indexed index, address indexed account, uint256 amount, uint256 vestingLength, uint256 cliffLength, uint256 vestingInterval ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../core/BaseUpgradeablePausable.sol"; import "../core/ConfigHelper.sol"; import "../core/CreditLine.sol"; import "../core/GoldfinchConfig.sol"; import "../../interfaces/IERC20withDec.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IBorrower.sol"; import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Goldfinch's Borrower contract * @notice These contracts represent the a convenient way for a borrower to interact with Goldfinch * They are 100% optional. However, they let us add many sophisticated and convient features for borrowers * while still keeping our core protocol small and secure. We therefore expect most borrowers will use them. * This contract is the "official" borrower contract that will be maintained by Goldfinch governance. However, * in theory, anyone can fork or create their own version, or not use any contract at all. The core functionality * is completely agnostic to whether it is interacting with a contract or an externally owned account (EOA). * @author Goldfinch */ contract Borrower is BaseUpgradeablePausable, BaseRelayRecipient, IBorrower { using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; address private constant USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); address private constant BUSD_ADDRESS = address(0x4Fabb145d64652a948d72533023f6E7A623C7C53); address private constant GUSD_ADDRESS = address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd); address private constant DAI_ADDRESS = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); function initialize(address owner, address _config) external override initializer { require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); trustedForwarder = config.trustedForwarderAddress(); // Handle default approvals. Pool, and OneInch for maximum amounts address oneInch = config.oneInchAddress(); IERC20withDec usdc = config.getUSDC(); usdc.approve(oneInch, uint256(-1)); bytes memory data = abi.encodeWithSignature("approve(address,uint256)", oneInch, uint256(-1)); invoke(USDT_ADDRESS, data); invoke(BUSD_ADDRESS, data); invoke(GUSD_ADDRESS, data); invoke(DAI_ADDRESS, data); } function lockJuniorCapital(address poolAddress) external onlyAdmin { ITranchedPool(poolAddress).lockJuniorCapital(); } function lockPool(address poolAddress) external onlyAdmin { ITranchedPool(poolAddress).lockPool(); } /** * @notice Allows a borrower to drawdown on their creditline through the CreditDesk. * @param poolAddress The creditline from which they would like to drawdown * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * @param addressToSendTo The address where they would like the funds sent. If the zero address is passed, * it will be defaulted to the contracts address (msg.sender). This is a convenience feature for when they would * like the funds sent to an exchange or alternate wallet, different from the authentication address */ function drawdown( address poolAddress, uint256 amount, address addressToSendTo ) external onlyAdmin { ITranchedPool(poolAddress).drawdown(amount); if (addressToSendTo == address(0) || addressToSendTo == address(this)) { addressToSendTo = _msgSender(); } transferERC20(config.usdcAddress(), addressToSendTo, amount); } function drawdownWithSwapOnOneInch( address poolAddress, uint256 amount, address addressToSendTo, address toToken, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) public onlyAdmin { // Drawdown to the Borrower contract ITranchedPool(poolAddress).drawdown(amount); // Do the swap swapOnOneInch(config.usdcAddress(), toToken, amount, minTargetAmount, exchangeDistribution); // Default to sending to the owner, and don't let funds stay in this contract if (addressToSendTo == address(0) || addressToSendTo == address(this)) { addressToSendTo = _msgSender(); } // Fulfill the send to bytes memory _data = abi.encodeWithSignature("balanceOf(address)", address(this)); uint256 receivedAmount = toUint256(invoke(toToken, _data)); transferERC20(toToken, addressToSendTo, receivedAmount); } function transferERC20( address token, address to, uint256 amount ) public onlyAdmin { bytes memory _data = abi.encodeWithSignature("transfer(address,uint256)", to, amount); invoke(token, _data); } /** * @notice Allows a borrower to payback loans by calling the `pay` function directly on the CreditDesk * @param poolAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that the borrower wishes to pay */ function pay(address poolAddress, uint256 amount) external onlyAdmin { IERC20withDec usdc = config.getUSDC(); bool success = usdc.transferFrom(_msgSender(), address(this), amount); require(success, "Failed to transfer USDC"); _transferAndPay(usdc, poolAddress, amount); } function payMultiple(address[] calldata pools, uint256[] calldata amounts) external onlyAdmin { require(pools.length == amounts.length, "Pools and amounts must be the same length"); uint256 totalAmount; for (uint256 i = 0; i < amounts.length; i++) { totalAmount = totalAmount.add(amounts[i]); } IERC20withDec usdc = config.getUSDC(); // Do a single transfer, which is cheaper bool success = usdc.transferFrom(_msgSender(), address(this), totalAmount); require(success, "Failed to transfer USDC"); for (uint256 i = 0; i < amounts.length; i++) { _transferAndPay(usdc, pools[i], amounts[i]); } } function payInFull(address poolAddress, uint256 amount) external onlyAdmin { IERC20withDec usdc = config.getUSDC(); bool success = usdc.transferFrom(_msgSender(), address(this), amount); require(success, "Failed to transfer USDC"); _transferAndPay(usdc, poolAddress, amount); require(ITranchedPool(poolAddress).creditLine().balance() == 0, "Failed to fully pay off creditline"); } function payWithSwapOnOneInch( address poolAddress, uint256 originAmount, address fromToken, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) external onlyAdmin { transferFrom(fromToken, _msgSender(), address(this), originAmount); IERC20withDec usdc = config.getUSDC(); swapOnOneInch(fromToken, address(usdc), originAmount, minTargetAmount, exchangeDistribution); uint256 usdcBalance = usdc.balanceOf(address(this)); _transferAndPay(usdc, poolAddress, usdcBalance); } function payMultipleWithSwapOnOneInch( address[] calldata pools, uint256[] calldata minAmounts, uint256 originAmount, address fromToken, uint256[] calldata exchangeDistribution ) external onlyAdmin { require(pools.length == minAmounts.length, "Pools and amounts must be the same length"); uint256 totalMinAmount = 0; for (uint256 i = 0; i < minAmounts.length; i++) { totalMinAmount = totalMinAmount.add(minAmounts[i]); } transferFrom(fromToken, _msgSender(), address(this), originAmount); IERC20withDec usdc = config.getUSDC(); swapOnOneInch(fromToken, address(usdc), originAmount, totalMinAmount, exchangeDistribution); for (uint256 i = 0; i < minAmounts.length; i++) { _transferAndPay(usdc, pools[i], minAmounts[i]); } uint256 remainingUSDC = usdc.balanceOf(address(this)); if (remainingUSDC > 0) { _transferAndPay(usdc, pools[0], remainingUSDC); } } function _transferAndPay( IERC20withDec usdc, address poolAddress, uint256 amount ) internal { ITranchedPool pool = ITranchedPool(poolAddress); // We don't use transferFrom since it would require a separate approval per creditline bool success = usdc.transfer(address(pool.creditLine()), amount); require(success, "USDC Transfer to creditline failed"); pool.assess(); } function transferFrom( address erc20, address sender, address recipient, uint256 amount ) internal { bytes memory _data; // Do a low-level invoke on this transfer, since Tether fails if we use the normal IERC20 interface _data = abi.encodeWithSignature("transferFrom(address,address,uint256)", sender, recipient, amount); invoke(address(erc20), _data); } function swapOnOneInch( address fromToken, address toToken, uint256 originAmount, uint256 minTargetAmount, uint256[] calldata exchangeDistribution ) internal { bytes memory _data = abi.encodeWithSignature( "swap(address,address,uint256,uint256,uint256[],uint256)", fromToken, toToken, originAmount, minTargetAmount, exchangeDistribution, 0 ); invoke(config.oneInchAddress(), _data); } /** * @notice Performs a generic transaction. * @param _target The address for the transaction. * @param _data The data of the transaction. * Mostly copied from Argent: * https://github.com/argentlabs/argent-contracts/blob/develop/contracts/wallet/BaseWallet.sol#L111 */ function invoke(address _target, bytes memory _data) internal returns (bytes memory) { // External contracts can be compiled with different Solidity versions // which can cause "revert without reason" when called through, // for example, a standard IERC20 ABI compiled on the latest version. // This low-level call avoids that issue. bool success; bytes memory _res; // solhint-disable-next-line avoid-low-level-calls (success, _res) = _target.call(_data); if (!success && _res.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } else if (!success) { revert("VM: wallet invoke reverted"); } return _res; } function toUint256(bytes memory _bytes) internal pure returns (uint256 value) { assembly { value := mload(add(_bytes, 0x20)) } } // OpenZeppelin contracts come with support for GSN _msgSender() (which just defaults to msg.sender) // Since there are two different versions of the function in the hierarchy, we need to instruct solidity to // use the relay recipient version which can actually pull the real sender from the parameters. // https://www.notion.so/My-contract-is-using-OpenZeppelin-How-do-I-add-GSN-support-2bee7e9d5f774a0cbb60d3a8de03e9fb function _msgSender() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (address payable) { return BaseRelayRecipient._msgSender(); } function _msgData() internal view override(ContextUpgradeSafe, BaseRelayRecipient) returns (bytes memory ret) { return BaseRelayRecipient._msgData(); } function versionRecipient() external view override returns (string memory) { return "2.0.0"; } } // SPDX-Licence-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IBorrower { function initialize(address owner, address _config) external; } // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity ^0.6.2; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(),20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr,32), size) calldatacopy(add(ptr,64), 0, size) return(ptr, add(size,64)) } } else { return msg.data; } } } // SPDX-License-Identifier:MIT pragma solidity ^0.6.2; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./GoldfinchConfig.sol"; import "./BaseUpgradeablePausable.sol"; import "../../interfaces/IBorrower.sol"; import "../../interfaces/ITranchedPool.sol"; import "./ConfigHelper.sol"; /** * @title GoldfinchFactory * @notice Contract that allows us to create other contracts, such as CreditLines and BorrowerContracts * Note GoldfinchFactory is a legacy name. More properly this can be considered simply the GoldfinchFactory * @author Goldfinch */ contract GoldfinchFactory is BaseUpgradeablePausable { GoldfinchConfig public config; /// Role to allow for pool creation bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE"); using ConfigHelper for GoldfinchConfig; event BorrowerCreated(address indexed borrower, address indexed owner); event PoolCreated(address indexed pool, address indexed borrower); event GoldfinchConfigUpdated(address indexed who, address configAddress); event CreditLineCreated(address indexed creditLine); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; _performUpgrade(); } function performUpgrade() external onlyAdmin { _performUpgrade(); } function _performUpgrade() internal { if (getRoleAdmin(BORROWER_ROLE) != OWNER_ROLE) { _setRoleAdmin(BORROWER_ROLE, OWNER_ROLE); } } /** * @notice Allows anyone to create a CreditLine contract instance * @dev There is no value to calling this function directly. It is only meant to be called * by a TranchedPool during it's creation process. */ function createCreditLine() external returns (address) { address creditLine = deployMinimal(config.creditLineImplementationAddress()); emit CreditLineCreated(creditLine); return creditLine; } /** * @notice Allows anyone to create a Borrower contract instance * @param owner The address that will own the new Borrower instance */ function createBorrower(address owner) external returns (address) { address _borrower = deployMinimal(config.borrowerImplementationAddress()); IBorrower borrower = IBorrower(_borrower); borrower.initialize(owner, address(config)); emit BorrowerCreated(address(borrower), owner); return address(borrower); } /** * @notice Allows anyone to create a new TranchedPool for a single borrower * @param _borrower The borrower for whom the CreditLine will be created * @param _juniorFeePercent The percent of senior interest allocated to junior investors, expressed as * integer percents. eg. 20% is simply 20 * @param _limit The maximum amount a borrower can drawdown from this CreditLine * @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer. * We assume 18 digits of precision. For example, to submit 15.34%, you would pass up 153400000000000000, * and 5.34% would be 53400000000000000 * @param _paymentPeriodInDays How many days in each payment period. * ie. the frequency with which they need to make payments. * @param _termInDays Number of days in the credit term. It is used to set the `termEndTime` upon first drawdown. * ie. The credit line should be fully paid off {_termIndays} days after the first drawdown. * @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your * normal rate is 15%, then you will pay 18% while you are late. Also expressed as an 18 decimal precision integer * * Requirements: * You are the admin */ function createPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) external onlyAdminOrBorrower returns (address pool) { address tranchedPoolImplAddress = config.tranchedPoolAddress(); pool = deployMinimal(tranchedPoolImplAddress); ITranchedPool(pool).initialize( address(config), _borrower, _juniorFeePercent, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays, _fundableAt, _allowedUIDTypes ); emit PoolCreated(pool, _borrower); config.getPoolTokens().onPoolCreated(pool); return pool; } function createMigratedPool( address _borrower, uint256 _juniorFeePercent, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr, uint256 _principalGracePeriodInDays, uint256 _fundableAt, uint256[] calldata _allowedUIDTypes ) external onlyCreditDesk returns (address pool) { address tranchedPoolImplAddress = config.migratedTranchedPoolAddress(); pool = deployMinimal(tranchedPoolImplAddress); ITranchedPool(pool).initialize( address(config), _borrower, _juniorFeePercent, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr, _principalGracePeriodInDays, _fundableAt, _allowedUIDTypes ); emit PoolCreated(pool, _borrower); config.getPoolTokens().onPoolCreated(pool); return pool; } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } // Stolen from: // https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/ProxyFactory.sol function deployMinimal(address _logic) internal returns (address proxy) { bytes20 targetBytes = bytes20(_logic); // solhint-disable-next-line no-inline-assembly assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } return proxy; } function isBorrower() public view returns (bool) { return hasRole(BORROWER_ROLE, _msgSender()); } modifier onlyAdminOrBorrower() { require(isAdmin() || isBorrower(), "Must have admin or borrower role to perform this action"); _; } modifier onlyCreditDesk() { require(msg.sender == config.creditDeskAddress(), "Only the CreditDesk can call this"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "../library/SafeERC20Transfer.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../interfaces/IPoolTokens.sol"; import "../interfaces/ITranchedPool.sol"; import "../interfaces/IBackerRewards.sol"; // Basically, Every time a interest payment comes back // we keep a running total of dollars (totalInterestReceived) until it reaches the maxInterestDollarsEligible limit // Every dollar of interest received from 0->maxInterestDollarsEligible // has a allocated amount of rewards based on a sqrt function. // When a interest payment comes in for a given Pool or the pool balance increases // we recalculate the pool's accRewardsPerPrincipalDollar // equation ref `_calculateNewGrossGFIRewardsForInterestAmount()`: // (sqrtNewTotalInterest - sqrtOrigTotalInterest) / sqrtMaxInterestDollarsEligible * (totalRewards / totalGFISupply) // When a PoolToken is minted, we set the mint price to the pool's current accRewardsPerPrincipalDollar // Every time a PoolToken withdraws rewards, we determine the allocated rewards, // increase that PoolToken's rewardsClaimed, and transfer the owner the gfi contract BackerRewards is IBackerRewards, BaseUpgradeablePausable, SafeERC20Transfer { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; struct BackerRewardsInfo { uint256 accRewardsPerPrincipalDollar; // accumulator gfi per interest dollar } struct BackerRewardsTokenInfo { uint256 rewardsClaimed; // gfi claimed uint256 accRewardsPerPrincipalDollarAtMint; // Pool's accRewardsPerPrincipalDollar at PoolToken mint() } uint256 public totalRewards; // total amount of GFI rewards available, times 1e18 uint256 public maxInterestDollarsEligible; // interest $ eligible for gfi rewards, times 1e18 uint256 public totalInterestReceived; // counter of total interest repayments, times 1e6 uint256 public totalRewardPercentOfTotalGFI; // totalRewards/totalGFISupply, times 1e18 mapping(uint256 => BackerRewardsTokenInfo) public tokens; // poolTokenId -> BackerRewardsTokenInfo mapping(address => BackerRewardsInfo) public pools; // pool.address -> BackerRewardsInfo // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Calculates the accRewardsPerPrincipalDollar for a given pool, when a interest payment is received by the protocol * @param _interestPaymentAmount The amount of total dollars the interest payment, expects 10^6 value */ function allocateRewards(uint256 _interestPaymentAmount) external override onlyPool { // note: do not use a require statment because that will TranchedPool kill execution if (_interestPaymentAmount > 0) { _allocateRewards(_interestPaymentAmount); } } /** * @notice Set the total gfi rewards and the % of total GFI * @param _totalRewards The amount of GFI rewards available, expects 10^18 value */ function setTotalRewards(uint256 _totalRewards) public onlyAdmin { totalRewards = _totalRewards; uint256 totalGFISupply = config.getGFI().totalSupply(); totalRewardPercentOfTotalGFI = _totalRewards.mul(mantissa()).div(totalGFISupply).mul(100); emit BackerRewardsSetTotalRewards(_msgSender(), _totalRewards, totalRewardPercentOfTotalGFI); } /** * @notice Set the total interest received to date. This should only be called once on contract deploy. * @param _totalInterestReceived The amount of interest the protocol has received to date, expects 10^6 value */ function setTotalInterestReceived(uint256 _totalInterestReceived) public onlyAdmin { totalInterestReceived = _totalInterestReceived; emit BackerRewardsSetTotalInterestReceived(_msgSender(), _totalInterestReceived); } /** * @notice Set the max dollars across the entire protocol that are eligible for GFI rewards * @param _maxInterestDollarsEligible The amount of interest dollars eligible for GFI rewards, expects 10^18 value */ function setMaxInterestDollarsEligible(uint256 _maxInterestDollarsEligible) public onlyAdmin { maxInterestDollarsEligible = _maxInterestDollarsEligible; emit BackerRewardsSetMaxInterestDollarsEligible(_msgSender(), _maxInterestDollarsEligible); } /** * @notice When a pool token is minted for multiple drawdowns, set accRewardsPerPrincipalDollarAtMint to the current accRewardsPerPrincipalDollar price * @param tokenId Pool token id */ function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external override { require(_msgSender() == config.poolTokensAddress(), "Invalid sender!"); require(config.getPoolTokens().validPool(poolAddress), "Invalid pool!"); if (tokens[tokenId].accRewardsPerPrincipalDollarAtMint != 0) { return; } IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); require(poolAddress == tokenInfo.pool, "PoolAddress must equal PoolToken pool address"); tokens[tokenId].accRewardsPerPrincipalDollarAtMint = pools[tokenInfo.pool].accRewardsPerPrincipalDollar; } /** * @notice Calculate the gross available gfi rewards for a PoolToken * @param tokenId Pool token id * @return The amount of GFI claimable */ function poolTokenClaimableRewards(uint256 tokenId) public view returns (uint256) { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); // Note: If a TranchedPool is oversubscribed, reward allocation's scale down proportionately. uint256 diffOfAccRewardsPerPrincipalDollar = pools[tokenInfo.pool].accRewardsPerPrincipalDollar.sub( tokens[tokenId].accRewardsPerPrincipalDollarAtMint ); uint256 rewardsClaimed = tokens[tokenId].rewardsClaimed.mul(mantissa()); /* equation for token claimable rewards: token.principalAmount * (pool.accRewardsPerPrincipalDollar - token.accRewardsPerPrincipalDollarAtMint) - token.rewardsClaimed */ return usdcToAtomic(tokenInfo.principalAmount).mul(diffOfAccRewardsPerPrincipalDollar).sub(rewardsClaimed).div( mantissa() ); } /** * @notice PoolToken request to withdraw multiple PoolTokens allocated rewards * @param tokenIds Array of pool token id */ function withdrawMultiple(uint256[] calldata tokenIds) public { require(tokenIds.length > 0, "TokensIds length must not be 0"); for (uint256 i = 0; i < tokenIds.length; i++) { withdraw(tokenIds[i]); } } /** * @notice PoolToken request to withdraw all allocated rewards * @param tokenId Pool token id */ function withdraw(uint256 tokenId) public { uint256 totalClaimableRewards = poolTokenClaimableRewards(tokenId); uint256 poolTokenRewardsClaimed = tokens[tokenId].rewardsClaimed; IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); address poolAddr = tokenInfo.pool; require(config.getPoolTokens().validPool(poolAddr), "Invalid pool!"); require(msg.sender == poolTokens.ownerOf(tokenId), "Must be owner of PoolToken"); BaseUpgradeablePausable pool = BaseUpgradeablePausable(poolAddr); require(!pool.paused(), "Pool withdraw paused"); ITranchedPool tranchedPool = ITranchedPool(poolAddr); require(!tranchedPool.creditLine().isLate(), "Pool is late on payments"); tokens[tokenId].rewardsClaimed = poolTokenRewardsClaimed.add(totalClaimableRewards); safeERC20Transfer(config.getGFI(), poolTokens.ownerOf(tokenId), totalClaimableRewards); emit BackerRewardsClaimed(_msgSender(), tokenId, totalClaimableRewards); } /* Internal functions */ function _allocateRewards(uint256 _interestPaymentAmount) internal { uint256 _totalInterestReceived = totalInterestReceived; if (usdcToAtomic(_totalInterestReceived) >= maxInterestDollarsEligible) { return; } address _poolAddress = _msgSender(); // Gross GFI Rewards earned for incoming interest dollars uint256 newGrossRewards = _calculateNewGrossGFIRewardsForInterestAmount(_interestPaymentAmount); ITranchedPool pool = ITranchedPool(_poolAddress); BackerRewardsInfo storage _poolInfo = pools[_poolAddress]; uint256 totalJuniorDeposits = pool.totalJuniorDeposits(); if (totalJuniorDeposits == 0) { return; } // example: (6708203932437400000000 * 10^18) / (100000*10^18) _poolInfo.accRewardsPerPrincipalDollar = _poolInfo.accRewardsPerPrincipalDollar.add( newGrossRewards.mul(mantissa()).div(usdcToAtomic(totalJuniorDeposits)) ); totalInterestReceived = _totalInterestReceived.add(_interestPaymentAmount); } /** * @notice Calculate the rewards earned for a given interest payment * @param _interestPaymentAmount interest payment amount times 1e6 */ function _calculateNewGrossGFIRewardsForInterestAmount(uint256 _interestPaymentAmount) internal view returns (uint256) { uint256 totalGFISupply = config.getGFI().totalSupply(); // incoming interest payment, times * 1e18 divided by 1e6 uint256 interestPaymentAmount = usdcToAtomic(_interestPaymentAmount); // all-time interest payments prior to the incoming amount, times 1e18 uint256 _previousTotalInterestReceived = usdcToAtomic(totalInterestReceived); uint256 sqrtOrigTotalInterest = Babylonian.sqrt(_previousTotalInterestReceived); // sum of new interest payment + previous total interest payments, times 1e18 uint256 newTotalInterest = usdcToAtomic( atomicToUSDC(_previousTotalInterestReceived).add(atomicToUSDC(interestPaymentAmount)) ); // interest payment passed the maxInterestDollarsEligible cap, should only partially be rewarded if (newTotalInterest > maxInterestDollarsEligible) { newTotalInterest = maxInterestDollarsEligible; } /* equation: (sqrtNewTotalInterest-sqrtOrigTotalInterest) * totalRewardPercentOfTotalGFI / sqrtMaxInterestDollarsEligible / 100 * totalGFISupply / 10^18 example scenario: - new payment = 5000*10^18 - original interest received = 0*10^18 - total reward percent = 3 * 10^18 - max interest dollars = 1 * 10^27 ($1 billion) - totalGfiSupply = 100_000_000 * 10^18 example math: (70710678118 - 0) * 3000000000000000000 / 31622776601683 / 100 * 100000000000000000000000000 / 10^18 = 6708203932437400000000 (6,708.2039 GFI) */ uint256 sqrtDiff = Babylonian.sqrt(newTotalInterest).sub(sqrtOrigTotalInterest); uint256 sqrtMaxInterestDollarsEligible = Babylonian.sqrt(maxInterestDollarsEligible); require(sqrtMaxInterestDollarsEligible > 0, "maxInterestDollarsEligible must not be zero"); uint256 newGrossRewards = sqrtDiff .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(mantissa()); // Extra safety check to make sure the logic is capped at a ceiling of potential rewards // Calculating the gfi/$ for first dollar of interest to the protocol, and multiplying by new interest amount uint256 absoluteMaxGfiCheckPerDollar = Babylonian .sqrt((uint256)(1).mul(mantissa())) .mul(totalRewardPercentOfTotalGFI) .div(sqrtMaxInterestDollarsEligible) .div(100) .mul(totalGFISupply) .div(mantissa()); require( newGrossRewards < absoluteMaxGfiCheckPerDollar.mul(newTotalInterest), "newGrossRewards cannot be greater then the max gfi per dollar" ); return newGrossRewards; } function mantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function usdcToAtomic(uint256 amount) internal pure returns (uint256) { return amount.mul(mantissa()).div(usdcMantissa()); } function atomicToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(mantissa().div(usdcMantissa())); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(_msgSender(), address(config)); } /* ======== MODIFIERS ======== */ modifier onlyPool() { require(config.getPoolTokens().validPool(_msgSender()), "Invalid pool!"); _; } /* ======== EVENTS ======== */ event GoldfinchConfigUpdated(address indexed who, address configAddress); event BackerRewardsClaimed(address indexed owner, uint256 indexed tokenId, uint256 amount); event BackerRewardsSetTotalRewards(address indexed owner, uint256 totalRewards, uint256 totalRewardPercentOfTotalGFI); event BackerRewardsSetTotalInterestReceived(address indexed owner, uint256 totalInterestReceived); event BackerRewardsSetMaxInterestDollarsEligible(address indexed owner, uint256 maxInterestDollarsEligible); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas 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); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../rewards/BackerRewards.sol"; contract TestBackerRewards is BackerRewards { address payable public sender; // solhint-disable-next-line modifiers/ensure-modifiers function _setSender(address payable _sender) public { sender = _sender; } function _msgSender() internal view override returns (address payable) { if (sender != address(0)) { return sender; } else { return super._msgSender(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "../../external/ERC721PresetMinterPauserAutoId.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/IFidu.sol"; import "../core/BaseUpgradeablePausable.sol"; import "../core/GoldfinchConfig.sol"; import "../core/ConfigHelper.sol"; import "../../library/SafeERC20Transfer.sol"; contract TransferRestrictedVault is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe, SafeERC20Transfer { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; struct PoolTokenPosition { uint256 tokenId; uint256 lockedUntil; } struct FiduPosition { uint256 amount; uint256 lockedUntil; } // tokenId => poolTokenPosition mapping(uint256 => PoolTokenPosition) public poolTokenPositions; // tokenId => fiduPosition mapping(uint256 => FiduPosition) public fiduPositions; /* We are using our own initializer function so that OZ doesn't automatically set owner as msg.sender. Also, it lets us set our config contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __AccessControl_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 Accredited Investor Tokens", "GFI-V2-AI"); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); config = _config; _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } function depositJunior(ITranchedPool tranchedPool, uint256 amount) public nonReentrant { require(config.getGo().go(msg.sender), "This address has not been go-listed"); safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); approveSpender(address(tranchedPool), amount); uint256 poolTokenId = tranchedPool.deposit(uint256(ITranchedPool.Tranches.Junior), amount); uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays()); _tokenIdTracker.increment(); uint256 tokenId = _tokenIdTracker.current(); poolTokenPositions[tokenId] = PoolTokenPosition({ tokenId: poolTokenId, lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds) }); _mint(msg.sender, tokenId); } function depositJuniorWithPermit( ITranchedPool tranchedPool, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); depositJunior(tranchedPool, amount); } function depositSenior(uint256 amount) public nonReentrant { safeERC20TransferFrom(config.getUSDC(), msg.sender, address(this), amount); ISeniorPool seniorPool = config.getSeniorPool(); approveSpender(address(seniorPool), amount); uint256 depositShares = seniorPool.deposit(amount); uint256 transferRestrictionPeriodInSeconds = SECONDS_PER_DAY.mul(config.getTransferRestrictionPeriodInDays()); _tokenIdTracker.increment(); uint256 tokenId = _tokenIdTracker.current(); fiduPositions[tokenId] = FiduPosition({ amount: depositShares, lockedUntil: block.timestamp.add(transferRestrictionPeriodInSeconds) }); _mint(msg.sender, tokenId); } function depositSeniorWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); depositSenior(amount); } function withdrawSenior(uint256 tokenId, uint256 usdcAmount) public nonReentrant onlyTokenOwner(tokenId) { IFidu fidu = config.getFidu(); ISeniorPool seniorPool = config.getSeniorPool(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); uint256 receivedAmount = seniorPool.withdraw(usdcAmount); uint256 fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); FiduPosition storage fiduPosition = fiduPositions[tokenId]; uint256 fiduPositionAmount = fiduPosition.amount; require(fiduPositionAmount >= fiduUsed, "Not enough Fidu for withdrawal"); fiduPosition.amount = fiduPositionAmount.sub(fiduUsed); safeERC20Transfer(config.getUSDC(), msg.sender, receivedAmount); } function withdrawSeniorInFidu(uint256 tokenId, uint256 shares) public nonReentrant onlyTokenOwner(tokenId) { FiduPosition storage fiduPosition = fiduPositions[tokenId]; uint256 fiduPositionAmount = fiduPosition.amount; require(fiduPositionAmount >= shares, "Not enough Fidu for withdrawal"); fiduPosition.amount = fiduPositionAmount.sub(shares); uint256 usdcAmount = config.getSeniorPool().withdrawInFidu(shares); safeERC20Transfer(config.getUSDC(), msg.sender, usdcAmount); } function withdrawJunior(uint256 tokenId, uint256 amount) public nonReentrant onlyTokenOwner(tokenId) returns (uint256 interestWithdrawn, uint256 principalWithdrawn) { PoolTokenPosition storage position = poolTokenPositions[tokenId]; require(position.lockedUntil > 0, "Position is empty"); IPoolTokens poolTokens = config.getPoolTokens(); uint256 poolTokenId = position.tokenId; IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(poolTokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (interestWithdrawn, principalWithdrawn) = pool.withdraw(poolTokenId, amount); uint256 totalWithdrawn = interestWithdrawn.add(principalWithdrawn); safeERC20Transfer(config.getUSDC(), msg.sender, totalWithdrawn); return (interestWithdrawn, principalWithdrawn); } function _beforeTokenTransfer( address from, address to, uint256 tokenId // solhint-disable-line no-unused-vars ) internal virtual override(ERC721PresetMinterPauserAutoIdUpgradeSafe) { // AccreditedInvestor tokens can never be transferred. The underlying positions, // however, can be transferred after the timelock expires. require(from == address(0) || to == address(0), "TransferRestrictedVault tokens cannot be transferred"); } /** * @dev This method assumes that positions are mutually exclusive i.e. that the token * represents a position in either PoolTokens or Fidu, but not both. */ function transferPosition(uint256 tokenId, address to) public nonReentrant { require(ownerOf(tokenId) == msg.sender, "Cannot transfer position of token you don't own"); FiduPosition storage fiduPosition = fiduPositions[tokenId]; if (fiduPosition.lockedUntil > 0) { require( block.timestamp >= fiduPosition.lockedUntil, "Underlying position cannot be transferred until lockedUntil" ); transferFiduPosition(fiduPosition, to); delete fiduPositions[tokenId]; } PoolTokenPosition storage poolTokenPosition = poolTokenPositions[tokenId]; if (poolTokenPosition.lockedUntil > 0) { require( block.timestamp >= poolTokenPosition.lockedUntil, "Underlying position cannot be transferred until lockedUntil" ); transferPoolTokenPosition(poolTokenPosition, to); delete poolTokenPositions[tokenId]; } _burn(tokenId); } function transferPoolTokenPosition(PoolTokenPosition storage position, address to) internal { IPoolTokens poolTokens = config.getPoolTokens(); poolTokens.safeTransferFrom(address(this), to, position.tokenId); } function transferFiduPosition(FiduPosition storage position, address to) internal { IFidu fidu = config.getFidu(); safeERC20Transfer(fidu, to, position.amount); } function approveSpender(address spender, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); safeERC20Approve(usdc, spender, allowance); } modifier onlyTokenOwner(uint256 tokenId) { require(ownerOf(tokenId) == msg.sender, "Only the token owner is allowed to call this function"); _; } } // SPDX-License-Identifier: MIT // solhint-disable pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // contract IOneSplitConsts { // // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ... // uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01; // uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated // uint256 internal constant FLAG_DISABLE_BANCOR = 0x04; // uint256 internal constant FLAG_DISABLE_OASIS = 0x08; // uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10; // uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20; // uint256 internal constant FLAG_DISABLE_CHAI = 0x40; // uint256 internal constant FLAG_DISABLE_AAVE = 0x80; // uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_BDAI = 0x400; // uint256 internal constant FLAG_DISABLE_IEARN = 0x800; // uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000; // uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000; // uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000; // uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000; // uint256 internal constant FLAG_DISABLE_WETH = 0x80000; // uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH // uint256 internal constant FLAG_DISABLE_IDLE = 0x800000; // uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000; // uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000; // uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000; // uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000; // uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000; // uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000; // uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000; // uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000; // uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000; // uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000; // uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000; // uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000; // uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000; // uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000; // uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000; // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default // uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default // uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000; // uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000; // uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_ALL = 0x8000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_ETH = 0x10000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_DAI = 0x20000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_USDC = 0x40000000000000000; // uint256 internal constant FLAG_DISABLE_MOONISWAP_POOL_TOKEN = 0x80000000000000000; // } interface IOneSplit { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) external view returns ( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) external payable returns (uint256 returnAmount); } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } pragma solidity ^0.6.0; import "./ERC20.sol"; import "../../utils/Pausable.sol"; import "../../Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; import "../../Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } pragma solidity ^0.6.0; import "../access/AccessControl.sol"; import "../GSN/Context.sol"; import "../token/ERC20/ERC20.sol"; import "../token/ERC20/ERC20Burnable.sol"; import "../token/ERC20/ERC20Pausable.sol"; import "../Initializable.sol"; /** * @dev {ERC20} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to aother accounts */ contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ function initialize(string memory name, string memory symbol) public { __ERC20PresetMinterPauser_init(name, symbol); } function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); __ERC20PresetMinterPauser_init_unchained(name, symbol); } function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) public { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint"); _mint(to, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) { super._beforeTokenTransfer(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol"; import "./ConfigHelper.sol"; /** * @title Fidu * @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares * in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we * burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu * and USDC (or whatever currencies the Pool may allow withdraws in during the future) * @author Goldfinch */ contract Fidu is ERC20PresetMinterPauserUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); // $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC; uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; event GoldfinchConfigUpdated(address indexed who, address configAddress); /* We are using our own initializer function so we can set the owner by passing it in. I would override the regular "initializer" function, but I can't because it's not marked as "virtual" in the parent contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__( address owner, string calldata name, string calldata symbol, GoldfinchConfig _config ) external initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __ERC20_init_unchained(name, symbol); __ERC20Burnable_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); config = _config; _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(MINTER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mintTo(address to, uint256 amount) public { require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch"); // This super call restricts to only the minter in its implementation, so we don't need to do it here. super.mint(to, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have the MINTER_ROLE */ function burnFrom(address from, uint256 amount) public override { require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn"); require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch"); _burn(from, amount); } // Internal functions // canMint assumes that the USDC that backs the new shares has already been sent to the Pool function canMint(uint256 newAmount) internal view returns (bool) { ISeniorPool seniorPool = config.getSeniorPool(); uint256 liabilities = totalSupply().add(newAmount).mul(seniorPool.sharePrice()).div(fiduMantissa()); uint256 liabilitiesInDollars = fiduToUSDC(liabilities); uint256 _assets = seniorPool.assets(); if (_assets >= liabilitiesInDollars) { return true; } else { return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD; } } // canBurn assumes that the USDC that backed these shares has already been moved out the Pool function canBurn(uint256 amountToBurn) internal view returns (bool) { ISeniorPool seniorPool = config.getSeniorPool(); uint256 liabilities = totalSupply().sub(amountToBurn).mul(seniorPool.sharePrice()).div(fiduMantissa()); uint256 liabilitiesInDollars = fiduToUSDC(liabilities); uint256 _assets = seniorPool.assets(); if (_assets >= liabilitiesInDollars) { return true; } else { return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD; } } function fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(fiduMantissa().div(usdcMantissa())); } function fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function updateGoldfinchConfig() external { require(hasRole(OWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to change config"); config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./LeverageRatioStrategy.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; contract FixedLeverageRatioStrategy is LeverageRatioStrategy { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) { return config.getLeverageRatio(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; abstract contract LeverageRatioStrategy is BaseUpgradeablePausable, ISeniorPoolStrategy { using SafeMath for uint256; uint256 internal constant LEVERAGE_RATIO_DECIMALS = 1e18; /** * @notice Determines how much money to invest in the senior tranche based on what is committed to the junior * tranche, what is committed to the senior tranche, and a leverage ratio to the junior tranche. Because * it takes into account what is already committed to the senior tranche, the value returned by this * function can be used "idempotently" to achieve the investment target amount without exceeding that target. * @param seniorPool The senior pool to invest from * @param pool The tranched pool to invest into (as the senior) * @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool */ function invest(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); // If junior capital is not yet invested, or pool already locked, then don't invest anything. if (juniorTranche.lockedUntil == 0 || seniorTranche.lockedUntil > 0) { return 0; } return _invest(pool, juniorTranche, seniorTranche); } /** * @notice A companion of `invest()`: determines how much would be returned by `invest()`, as the * value to invest into the senior tranche, if the junior tranche were locked and the senior tranche * were not locked. * @param seniorPool The senior pool to invest from * @param pool The tranched pool to invest into (as the senior) * @return The amount of money to invest into the tranched pool's senior tranche, from the senior pool */ function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view override returns (uint256) { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); return _invest(pool, juniorTranche, seniorTranche); } function _invest( ITranchedPool pool, ITranchedPool.TrancheInfo memory juniorTranche, ITranchedPool.TrancheInfo memory seniorTranche ) internal view returns (uint256) { uint256 juniorCapital = juniorTranche.principalDeposited; uint256 existingSeniorCapital = seniorTranche.principalDeposited; uint256 seniorTarget = juniorCapital.mul(getLeverageRatio(pool)).div(LEVERAGE_RATIO_DECIMALS); if (existingSeniorCapital >= seniorTarget) { return 0; } return seniorTarget.sub(existingSeniorCapital); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./LeverageRatioStrategy.sol"; import "../../interfaces/ISeniorPoolStrategy.sol"; import "../../interfaces/ISeniorPool.sol"; import "../../interfaces/ITranchedPool.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; contract DynamicLeverageRatioStrategy is LeverageRatioStrategy { bytes32 public constant LEVERAGE_RATIO_SETTER_ROLE = keccak256("LEVERAGE_RATIO_SETTER_ROLE"); struct LeverageRatioInfo { uint256 leverageRatio; uint256 juniorTrancheLockedUntil; } // tranchedPoolAddress => leverageRatioInfo mapping(address => LeverageRatioInfo) public ratios; event LeverageRatioUpdated( address indexed pool, uint256 leverageRatio, uint256 juniorTrancheLockedUntil, bytes32 version ); function initialize(address owner) public initializer { require(owner != address(0), "Owner address cannot be empty"); __BaseUpgradeablePausable__init(owner); _setupRole(LEVERAGE_RATIO_SETTER_ROLE, owner); _setRoleAdmin(LEVERAGE_RATIO_SETTER_ROLE, OWNER_ROLE); } function getLeverageRatio(ITranchedPool pool) public view override returns (uint256) { LeverageRatioInfo memory ratioInfo = ratios[address(pool)]; ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); require(ratioInfo.juniorTrancheLockedUntil > 0, "Leverage ratio has not been set yet."); if (seniorTranche.lockedUntil > 0) { // The senior tranche is locked. Coherence check: we expect locking the senior tranche to have // updated `juniorTranche.lockedUntil` (compared to its value when `setLeverageRatio()` was last // called successfully). require( ratioInfo.juniorTrancheLockedUntil < juniorTranche.lockedUntil, "Expected junior tranche `lockedUntil` to have been updated." ); } else { require( ratioInfo.juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Leverage ratio is obsolete. Wait for its recalculation." ); } return ratioInfo.leverageRatio; } /** * @notice Updates the leverage ratio for the specified tranched pool. The combination of the * `juniorTranchedLockedUntil` param and the `version` param in the event emitted by this * function are intended to enable an outside observer to verify the computation of the leverage * ratio set by calls of this function. * @param pool The tranched pool whose leverage ratio to update. * @param leverageRatio The leverage ratio value to set for the tranched pool. * @param juniorTrancheLockedUntil The `lockedUntil` timestamp, of the tranched pool's * junior tranche, to which this calculation of `leverageRatio` corresponds, i.e. the * value of the `lockedUntil` timestamp of the JuniorCapitalLocked event which the caller * is calling this function in response to having observed. By providing this timestamp * (plus an assumption that we can trust the caller to report this value accurately), * the caller enables this function to enforce that a leverage ratio that is obsolete in * the sense of having been calculated for an obsolete `lockedUntil` timestamp cannot be set. * @param version An arbitrary identifier included in the LeverageRatioUpdated event emitted * by this function, enabling the caller to describe how it calculated `leverageRatio`. Using * the bytes32 type accommodates using git commit hashes (both the current SHA1 hashes, which * require 20 bytes; and the future SHA256 hashes, which require 32 bytes) for this value. */ function setLeverageRatio( ITranchedPool pool, uint256 leverageRatio, uint256 juniorTrancheLockedUntil, bytes32 version ) public onlySetterRole { ITranchedPool.TrancheInfo memory juniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Junior)); ITranchedPool.TrancheInfo memory seniorTranche = pool.getTranche(uint256(ITranchedPool.Tranches.Senior)); // NOTE: We allow a `leverageRatio` of 0. require( leverageRatio <= 10 * LEVERAGE_RATIO_DECIMALS, "Leverage ratio must not exceed 10 (adjusted for decimals)." ); require(juniorTranche.lockedUntil > 0, "Cannot set leverage ratio if junior tranche is not locked."); require(seniorTranche.lockedUntil == 0, "Cannot set leverage ratio if senior tranche is locked."); require(juniorTrancheLockedUntil == juniorTranche.lockedUntil, "Invalid `juniorTrancheLockedUntil` timestamp."); ratios[address(pool)] = LeverageRatioInfo({ leverageRatio: leverageRatio, juniorTrancheLockedUntil: juniorTrancheLockedUntil }); emit LeverageRatioUpdated(address(pool), leverageRatio, juniorTrancheLockedUntil, version); } modifier onlySetterRole() { require( hasRole(LEVERAGE_RATIO_SETTER_ROLE, _msgSender()), "Must have leverage-ratio setter role to perform this action" ); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.5 <0.8.0; import "../token/ERC20/ERC20.sol"; import "./IERC20Permit.sol"; import "../cryptography/ECDSA.sol"; import "../utils/Counters.sol"; import "./EIP712.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) internal EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) internal { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // 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.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 "./ERC20.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.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.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol"; /** * @title GFI * @notice GFI is Goldfinch's governance token. * @author Goldfinch */ contract GFI is Context, AccessControl, ERC20Burnable, ERC20Pausable { using SafeMath for uint256; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /// The maximum number of tokens that can be minted uint256 public cap; event CapUpdated(address indexed who, uint256 cap); constructor( address owner, string memory name, string memory symbol, uint256 initialCap ) public ERC20(name, symbol) { cap = initialCap; _setupRole(MINTER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(MINTER_ROLE, OWNER_ROLE); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @notice create and send tokens to a specified address * @dev this function will fail if the caller attempts to mint over the current cap */ function mint(address account, uint256 amount) public onlyMinter whenNotPaused { require(mintingAmountIsWithinCap(amount), "Cannot mint more than cap"); _mint(account, amount); } /** * @notice sets the maximum number of tokens that can be minted * @dev the cap must be greater than the current total supply */ function setCap(uint256 _cap) external onlyOwner { require(_cap >= totalSupply(), "Cannot decrease the cap below existing supply"); cap = _cap; emit CapUpdated(_msgSender(), cap); } function mintingAmountIsWithinCap(uint256 amount) internal returns (bool) { return totalSupply().add(amount) <= cap; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external onlyPauser { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external onlyPauser { _unpause(); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } modifier onlyOwner() { require(hasRole(OWNER_ROLE, _msgSender()), "Must be owner"); _; } modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Must be minter"); _; } modifier onlyPauser() { require(hasRole(PAUSER_ROLE, _msgSender()), "Must be pauser"); _; } } // 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 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.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; // Taken from https://github.com/opengsn/forwarder/blob/master/contracts/Forwarder.sol and adapted to work locally // Main change is removing interface inheritance and adding a some debugging niceities contract TestForwarder { using ECDSA for bytes32; struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; } string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data"; string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; // solhint-disable-line max-line-length mapping(bytes32 => bool) public typeHashes; mapping(bytes32 => bool) public domains; // Nonces of senders, used to prevent replay attacks mapping(address => uint256) private nonces; // solhint-disable-next-line no-empty-blocks receive() external payable {} function getNonce(address from) public view returns (uint256) { return nonces[from]; } constructor() public { string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")")); registerRequestTypeInternal(requestType); } function verify( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external view { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); } function execute( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external payable returns (bool success, bytes memory ret) { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); _updateNonce(req); // solhint-disable-next-line avoid-low-level-calls (success, ret) = req.to.call{gas: req.gas, value: req.value}(abi.encodePacked(req.data, req.from)); // Added by Goldfinch for debugging if (!success) { require(success, string(ret)); } if (address(this).balance > 0) { //can't fail: req.from signed (off-chain) the request, so it must be an EOA... payable(req.from).transfer(address(this).balance); } return (success, ret); } function _verifyNonce(ForwardRequest memory req) internal view { require(nonces[req.from] == req.nonce, "nonce mismatch"); } function _updateNonce(ForwardRequest memory req) internal { nonces[req.from]++; } function registerRequestType(string calldata typeName, string calldata typeSuffix) external { for (uint256 i = 0; i < bytes(typeName).length; i++) { bytes1 c = bytes(typeName)[i]; require(c != "(" && c != ")", "invalid typename"); } string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix)); registerRequestTypeInternal(requestType); } function registerDomainSeparator(string calldata name, string calldata version) external { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } bytes memory domainValue = abi.encode( keccak256(bytes(EIP712_DOMAIN_TYPE)), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ); bytes32 domainHash = keccak256(domainValue); domains[domainHash] = true; emit DomainRegistered(domainHash, domainValue); } function registerRequestTypeInternal(string memory requestType) internal { bytes32 requestTypehash = keccak256(bytes(requestType)); typeHashes[requestTypehash] = true; emit RequestTypeRegistered(requestTypehash, requestType); } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function _verifySig( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig ) internal view { require(domains[domainSeparator], "unregistered domain separator"); require(typeHashes[requestTypeHash], "unregistered request typehash"); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData))) ); require(digest.recover(sig) == req.from, "signature mismatch"); } function _getEncoded( ForwardRequest memory req, bytes32 requestTypeHash, bytes memory suffixData ) public pure returns (bytes memory) { return abi.encodePacked( requestTypeHash, abi.encode(req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data)), suffixData ); } } // contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/drafts/ERC20Permit.sol"; contract TestERC20 is ERC20("USD Coin", "USDC"), ERC20Permit("USD Coin") { constructor(uint256 initialSupply, uint8 decimals) public { _setupDecimals(decimals); _mint(msg.sender, initialSupply); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../external/ERC721PresetMinterPauserAutoId.sol"; import "./GoldfinchConfig.sol"; import "./ConfigHelper.sol"; import "../../interfaces/ITranchedPool.sol"; import "../../interfaces/IPoolTokens.sol"; /** * @title PoolTokens * @notice PoolTokens is an ERC721 compliant contract, which can represent * junior tranche or senior tranche shares of any of the borrower pools. * @author Goldfinch */ contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe { bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct PoolInfo { uint256 totalMinted; uint256 totalPrincipalRedeemed; bool created; } // tokenId => tokenInfo mapping(uint256 => TokenInfo) public tokens; // poolAddress => poolInfo mapping(address => PoolInfo) public pools; event TokenMinted( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 amount, uint256 tranche ); event TokenRedeemed( address indexed owner, address indexed pool, uint256 indexed tokenId, uint256 principalRedeemed, uint256 interestRedeemed, uint256 tranche ); event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId); event GoldfinchConfigUpdated(address indexed who, address configAddress); /* We are using our own initializer function so that OZ doesn't automatically set owner as msg.sender. Also, it lets us set our config contract */ // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __Context_init_unchained(); __AccessControl_init_unchained(); __ERC165_init_unchained(); // This is setting name and symbol of the NFT's __ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT"); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); config = _config; _setupRole(PAUSER_ROLE, owner); _setupRole(OWNER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); } /** * @notice Called by pool to create a debt position in a particular tranche and amount * @param params Struct containing the tranche and the amount * @param to The address that should own the position * @return tokenId The token ID (auto-incrementing integer across all pools) */ function mint(MintParams calldata params, address to) external virtual override onlyPool whenNotPaused returns (uint256 tokenId) { address poolAddress = _msgSender(); tokenId = createToken(params, poolAddress); _mint(to, tokenId); config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId); emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche); return tokenId; } /** * @notice Updates a token to reflect the principal and interest amounts that have been redeemed. * @param tokenId The token id to update (must be owned by the pool calling this function) * @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited) * @param interestRedeemed The incremental amount of interest redeemed */ function redeem( uint256 tokenId, uint256 principalRedeemed, uint256 interestRedeemed ) external virtual override onlyPool whenNotPaused { TokenInfo storage token = tokens[tokenId]; address poolAddr = token.pool; require(token.pool != address(0), "Invalid tokenId"); require(_msgSender() == poolAddr, "Only the token's pool can redeem"); PoolInfo storage pool = pools[poolAddr]; pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed); require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted"); token.principalRedeemed = token.principalRedeemed.add(principalRedeemed); require( token.principalRedeemed <= token.principalAmount, "Cannot redeem more than principal-deposited amount for token" ); token.interestRedeemed = token.interestRedeemed.add(interestRedeemed); emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche); } /** * @dev Burns a specific ERC721 token, and removes the data from our mappings * @param tokenId uint256 id of the ERC721 token to be burned. */ function burn(uint256 tokenId) external virtual override whenNotPaused { TokenInfo memory token = _getTokenInfo(tokenId); bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId); bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender(); address owner = ownerOf(tokenId); require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token"); require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens"); destroyAndBurn(tokenId); emit TokenBurned(owner, token.pool, tokenId); } function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) { return _getTokenInfo(tokenId); } /** * @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem * tokens * @param newPool The address of the newly created pool */ function onPoolCreated(address newPool) external override onlyGoldfinchFactory { pools[newPool].created = true; } /** * @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token * @param spender The address to check * @param tokenId The token id to check for * @return True if approved to redeem/transfer/burn the token, false if not */ function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function validPool(address sender) public view virtual override returns (bool) { return _validPool(sender); } function createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) { PoolInfo storage pool = pools[poolAddress]; _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); tokens[tokenId] = TokenInfo({ pool: poolAddress, tranche: params.tranche, principalAmount: params.principalAmount, principalRedeemed: 0, interestRedeemed: 0 }); pool.totalMinted = pool.totalMinted.add(params.principalAmount); return tokenId; } function destroyAndBurn(uint256 tokenId) internal { delete tokens[tokenId]; _burn(tokenId); } function _validPool(address poolAddress) internal view virtual returns (bool) { return pools[poolAddress].created; } function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) { return tokens[tokenId]; } /** * @notice Migrates to a new goldfinch config address */ function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } modifier onlyAdmin() { require(isAdmin(), "Must have admin role to perform this action"); _; } function isAdmin() public view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyGoldfinchFactory() { require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed"); _; } modifier onlyPool() { require(_validPool(_msgSender()), "Invalid pool!"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/PoolTokens.sol"; contract TestPoolTokens is PoolTokens { bool public disablePoolValidation; address payable public sender; // solhint-disable-next-line modifiers/ensure-modifiers function _disablePoolValidation(bool shouldDisable) public { disablePoolValidation = shouldDisable; } // solhint-disable-next-line modifiers/ensure-modifiers function _setSender(address payable _sender) public { sender = _sender; } function _validPool(address _sender) internal view override returns (bool) { if (disablePoolValidation) { return true; } else { return super._validPool(_sender); } } function _msgSender() internal view override returns (address payable) { if (sender != address(0)) { return sender; } else { return super._msgSender(); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./IV2CreditLine.sol"; import "./IV1CreditLine.sol"; import "./ITranchedPool.sol"; abstract contract IMigratedTranchedPool is ITranchedPool { function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external virtual returns (IV2CreditLine); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IV1CreditLine { address public borrower; address public underwriter; uint256 public limit; uint256 public interestApr; uint256 public paymentPeriodInDays; uint256 public termInDays; uint256 public lateFeeApr; uint256 public balance; uint256 public interestOwed; uint256 public principalOwed; uint256 public termEndBlock; uint256 public nextDueBlock; uint256 public interestAccruedAsOfBlock; uint256 public writedownAmount; uint256 public lastFullPaymentBlock; function setLimit(uint256 newAmount) external virtual; function setBalance(uint256 newBalance) external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./TranchedPool.sol"; import "../../interfaces/IV1CreditLine.sol"; import "../../interfaces/IMigratedTranchedPool.sol"; contract MigratedTranchedPool is TranchedPool, IMigratedTranchedPool { bool public migrated; function migrateCreditLineToV2( IV1CreditLine clToMigrate, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) external override returns (IV2CreditLine) { require(msg.sender == config.creditDeskAddress(), "Only credit desk can call this"); require(!migrated, "Already migrated"); // Set accounting state vars. IV2CreditLine newCl = creditLine; newCl.setBalance(clToMigrate.balance()); newCl.setInterestOwed(clToMigrate.interestOwed()); newCl.setPrincipalOwed(clToMigrate.principalOwed()); newCl.setTermEndTime(termEndTime); newCl.setNextDueTime(nextDueTime); newCl.setInterestAccruedAsOf(interestAccruedAsOf); newCl.setLastFullPaymentTime(lastFullPaymentTime); newCl.setTotalInterestAccrued(totalInterestPaid.add(clToMigrate.interestOwed())); migrateDeposits(clToMigrate, totalInterestPaid); migrated = true; return newCl; } function migrateDeposits(IV1CreditLine clToMigrate, uint256 totalInterestPaid) internal { // Mint junior tokens to the SeniorPool, equal to current cl balance; require(!locked(), "Pool has been locked"); // Hardcode to always get the JuniorTranche, since the migration case is when // the senior pool took the entire investment. Which we're expressing as the junior tranche uint256 tranche = uint256(ITranchedPool.Tranches.Junior); TrancheInfo storage trancheInfo = getTrancheInfo(tranche); require(trancheInfo.lockedUntil == 0, "Tranche has been locked"); trancheInfo.principalDeposited = clToMigrate.limit(); IPoolTokens.MintParams memory params = IPoolTokens.MintParams({ tranche: tranche, principalAmount: trancheInfo.principalDeposited }); IPoolTokens poolTokens = config.getPoolTokens(); uint256 tokenId = poolTokens.mint(params, config.seniorPoolAddress()); uint256 balancePaid = creditLine.limit().sub(creditLine.balance()); // Account for the implicit redemptions already made by the Legacy Pool _lockJuniorCapital(poolSlices.length - 1); _lockPool(); PoolSlice storage currentSlice = poolSlices[poolSlices.length - 1]; currentSlice.juniorTranche.lockedUntil = block.timestamp - 1; poolTokens.redeem(tokenId, balancePaid, totalInterestPaid); // Simulate the drawdown currentSlice.juniorTranche.principalSharePrice = 0; currentSlice.seniorTranche.principalSharePrice = 0; // Set junior's sharePrice correctly currentSlice.juniorTranche.applyByAmount(totalInterestPaid, balancePaid, totalInterestPaid, balancePaid); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "./Accountant.sol"; import "./CreditLine.sol"; import "./GoldfinchFactory.sol"; import "../../interfaces/IV1CreditLine.sol"; import "../../interfaces/IMigratedTranchedPool.sol"; /** * @title Goldfinch's CreditDesk contract * @notice Main entry point for borrowers and underwriters. * Handles key logic for creating CreditLine's, borrowing money, repayment, etc. * @author Goldfinch */ contract CreditDesk is BaseUpgradeablePausable, ICreditDesk { uint256 public constant SECONDS_PER_DAY = 60 * 60 * 24; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; struct Underwriter { uint256 governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentApplied( address indexed payer, address indexed creditLine, uint256 interestAmount, uint256 principalAmount, uint256 remainingAmount ); event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; mapping(address => address) private creditLines; /** * @notice Run only once, on initialization * @param owner The address of who should have the "OWNER_ROLE" of this contract * @param _config The address of the GoldfinchConfig contract */ function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; } /** * @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create" * @param underwriterAddress The address of the underwriter for whom the limit shall change * @param limit What the new limit will be set to * Requirements: * * - the caller must have the `OWNER_ROLE`. */ function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external override onlyAdmin whenNotPaused { require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol"); underwriters[underwriterAddress].governanceLimit = limit; emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit); } /** * @notice Allows a borrower to drawdown on their creditline. * `amount` USDC is sent to the borrower, and the credit line accounting is updated. * @param creditLineAddress The creditline from which they would like to drawdown * @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown * * Requirements: * * - the caller must be the borrower on the creditLine */ function drawdown(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); Borrower storage borrower = borrowers[msg.sender]; require(borrower.creditLines.length > 0, "No credit lines exist for this borrower"); require(amount > 0, "Must drawdown more than zero"); require(cl.borrower() == msg.sender, "You are not the borrower of this credit line"); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); uint256 unappliedBalance = getUSDCBalance(creditLineAddress); require( withinCreditLimit(amount, unappliedBalance, cl), "The borrower does not have enough credit limit for this drawdown" ); uint256 balance = cl.balance(); if (balance == 0) { cl.setInterestAccruedAsOf(currentTime()); cl.setLastFullPaymentTime(currentTime()); } IPool pool = config.getPool(); // If there is any balance on the creditline that has not been applied yet, then use that first before // drawing down from the pool. This is to support cases where the borrower partially pays back the // principal before the due date, but then decides to drawdown again uint256 amountToTransferFromCL; if (unappliedBalance > 0) { if (amount > unappliedBalance) { amountToTransferFromCL = unappliedBalance; amount = amount.sub(unappliedBalance); } else { amountToTransferFromCL = amount; amount = 0; } bool success = pool.transferFrom(creditLineAddress, msg.sender, amountToTransferFromCL); require(success, "Failed to drawdown"); } (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, currentTime()); balance = balance.add(amount); updateCreditLineAccounting(cl, balance, interestOwed, principalOwed); // Must put this after we update the credit line accounting, so we're using the latest // interestOwed require(!isLate(cl, currentTime()), "Cannot drawdown when payments are past due"); emit DrawdownMade(msg.sender, address(cl), amount.add(amountToTransferFromCL)); if (amount > 0) { bool success = pool.drawdown(msg.sender, amount); require(success, "Failed to drawdown"); } } /** * @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to * the individual CreditLine), but it is not *applied* unless it is after the nextDueTime, or until we assess * the credit line (ie. payment period end). * Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective * interest rate). If there is still any left over, it will remain in the USDC Balance * of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's. * @param creditLineAddress The credit line to be paid back * @param amount The amount, in USDC atomic units, that a borrower wishes to pay */ function pay(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { require(amount > 0, "Must pay more than zero"); CreditLine cl = CreditLine(creditLineAddress); collectPayment(cl, amount); assessCreditLine(creditLineAddress); } /** * @notice Assesses a particular creditLine. This will apply payments, which will update accounting and * distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone * is allowed to call it. * @param creditLineAddress The creditline that should be assessed. */ function assessCreditLine(address creditLineAddress) public override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); // Do not assess until a full period has elapsed or past due require(cl.balance() > 0, "Must have balance to assess credit line"); // Don't assess credit lines early! if (currentTime() < cl.nextDueTime() && !isLate(cl, currentTime())) { return; } uint256 timeToAssess = calculateNextDueTime(cl); cl.setNextDueTime(timeToAssess); // We always want to assess for the most recently *past* nextDueTime. // So if the recalculation above sets the nextDueTime into the future, // then ensure we pass in the one just before this. if (timeToAssess > currentTime()) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); timeToAssess = timeToAssess.sub(secondsPerPeriod); } _applyPayment(cl, getUSDCBalance(address(cl)), timeToAssess); } function applyPayment(address creditLineAddress, uint256 amount) external override whenNotPaused onlyValidCreditLine(creditLineAddress) { CreditLine cl = CreditLine(creditLineAddress); require(cl.borrower() == msg.sender, "You do not belong to this credit line"); _applyPayment(cl, amount, currentTime()); } function migrateV1CreditLine( address _clToMigrate, address borrower, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) public onlyAdmin returns (address, address) { IV1CreditLine clToMigrate = IV1CreditLine(_clToMigrate); uint256 originalBalance = clToMigrate.balance(); require(clToMigrate.limit() > 0, "Can't migrate empty credit line"); require(originalBalance > 0, "Can't migrate credit line that's currently paid off"); // Ensure it is a v1 creditline by calling a function that only exists on v1 require(clToMigrate.nextDueBlock() > 0, "Invalid creditline"); if (borrower == address(0)) { borrower = clToMigrate.borrower(); } // We're migrating from 1e8 decimal precision of interest rates to 1e18 // So multiply the legacy rates by 1e10 to normalize them. uint256 interestMigrationFactor = 1e10; uint256[] memory allowedUIDTypes; address pool = getGoldfinchFactory().createMigratedPool( borrower, 20, // junior fee percent clToMigrate.limit(), clToMigrate.interestApr().mul(interestMigrationFactor), clToMigrate.paymentPeriodInDays(), clToMigrate.termInDays(), clToMigrate.lateFeeApr(), 0, 0, allowedUIDTypes ); IV2CreditLine newCl = IMigratedTranchedPool(pool).migrateCreditLineToV2( clToMigrate, termEndTime, nextDueTime, interestAccruedAsOf, lastFullPaymentTime, totalInterestPaid ); // Close out the original credit line clToMigrate.setLimit(0); clToMigrate.setBalance(0); // Some sanity checks on the migration require(newCl.balance() == originalBalance, "Balance did not migrate properly"); require(newCl.interestAccruedAsOf() == interestAccruedAsOf, "Interest accrued as of did not migrate properly"); return (address(newCl), pool); } /** * @notice Simple getter for the creditlines of a given underwriter * @param underwriterAddress The underwriter address you would like to see the credit lines of. */ function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } /** * @notice Simple getter for the creditlines of a given borrower * @param borrowerAddress The borrower address you would like to see the credit lines of. */ function getBorrowerCreditLines(address borrowerAddress) public view returns (address[] memory) { return borrowers[borrowerAddress].creditLines; } /** * @notice This function is only meant to be used by frontends. It returns the total * payment due for a given creditLine as of the provided timestamp. Returns 0 if no * payment is due (e.g. asOf is before the nextDueTime) * @param creditLineAddress The creditLine to calculate the payment for * @param asOf The timestamp to use for the payment calculation, if it is set to 0, uses the current time */ function getNextPaymentAmount(address creditLineAddress, uint256 asOf) external view override onlyValidCreditLine(creditLineAddress) returns (uint256) { if (asOf == 0) { asOf = currentTime(); } CreditLine cl = CreditLine(creditLineAddress); if (asOf < cl.nextDueTime() && !isLate(cl, currentTime())) { return 0; } (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( cl, asOf, config.getLatenessGracePeriodInDays() ); return cl.interestOwed().add(interestAccrued).add(cl.principalOwed().add(principalAccrued)); } function updateGoldfinchConfig() external onlyAdmin { config = GoldfinchConfig(config.configAddress()); } /* * Internal Functions */ /** * @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line. * Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be collected */ function collectPayment(CreditLine cl, uint256 amount) internal { require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); emit PaymentCollected(msg.sender, address(cl), amount); bool success = config.getPool().transferFrom(msg.sender, address(cl), amount); require(success, "Failed to collect payment"); } /** * @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool. * It also updates all the accounting variables. Note that interest is always paid back first, then principal. * Any extra after paying the minimum will go towards existing principal (reducing the * effective interest rate). Any extra after the full loan has been paid off will remain in the * USDC Balance of the creditLine, where it will be automatically used for the next drawdown. * @param cl The CreditLine the payment will be collected for. * @param amount The amount, in USDC atomic units, to be applied * @param timestamp The timestamp on which accrual calculations should be based. This allows us * to be precise when we assess a Credit Line */ function _applyPayment( CreditLine cl, uint256 amount, uint256 timestamp ) internal { (uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) = handlePayment( cl, amount, timestamp ); IPool pool = config.getPool(); if (interestPayment > 0 || principalPayment > 0) { emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); pool.collectInterestAndPrincipal(address(cl), interestPayment, principalPayment); } } function handlePayment( CreditLine cl, uint256 paymentAmount, uint256 timestamp ) internal returns ( uint256, uint256, uint256 ) { (uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, timestamp); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment( paymentAmount, cl.balance(), interestOwed, principalOwed ); uint256 newBalance = cl.balance().sub(pa.principalPayment); // Apply any additional payment towards the balance newBalance = newBalance.sub(pa.additionalBalancePayment); uint256 totalPrincipalPayment = cl.balance().sub(newBalance); uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting( cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment) ); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function isLate(CreditLine cl, uint256 timestamp) internal view returns (bool) { uint256 secondsElapsedSinceFullPayment = timestamp.sub(cl.lastFullPaymentTime()); return secondsElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); } function getGoldfinchFactory() internal view returns (GoldfinchFactory) { return GoldfinchFactory(config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory))); } function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 timestamp) internal returns (uint256, uint256) { (uint256 interestAccrued, uint256 principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued( cl, timestamp, config.getLatenessGracePeriodInDays() ); if (interestAccrued > 0) { // If we've accrued any interest, update interestAccruedAsOf to the time that we've // calculated interest for. If we've not accrued any interest, then we keep the old value so the next // time the entire period is taken into account. cl.setInterestAccruedAsOf(timestamp); } return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued)); } function withinCreditLimit( uint256 amount, uint256 unappliedBalance, CreditLine cl ) internal view returns (bool) { return cl.balance().add(amount).sub(unappliedBalance) <= cl.limit(); } function withinTransactionLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit)); } function calculateNewTermEndTime(CreditLine cl, uint256 balance) internal view returns (uint256) { // If there's no balance, there's no loan, so there's no term end time if (balance == 0) { return 0; } // Don't allow any weird bugs where we add to your current end time. This // function should only be used on new credit lines, when we are setting them up if (cl.termEndTime() != 0) { return cl.termEndTime(); } return currentTime().add(SECONDS_PER_DAY.mul(cl.termInDays())); } function calculateNextDueTime(CreditLine cl) internal view returns (uint256) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); uint256 balance = cl.balance(); uint256 nextDueTime = cl.nextDueTime(); uint256 curTimestamp = currentTime(); // You must have just done your first drawdown if (nextDueTime == 0 && balance > 0) { return curTimestamp.add(secondsPerPeriod); } // Active loan that has entered a new period, so return the *next* nextDueTime. // But never return something after the termEndTime if (balance > 0 && curTimestamp >= nextDueTime) { uint256 secondsToAdvance = (curTimestamp.sub(nextDueTime).div(secondsPerPeriod)).add(1).mul(secondsPerPeriod); nextDueTime = nextDueTime.add(secondsToAdvance); return Math.min(nextDueTime, cl.termEndTime()); } // Your paid off, or have not taken out a loan yet, so no next due time. if (balance == 0 && nextDueTime != 0) { return 0; } // Active loan in current period, where we've already set the nextDueTime correctly, so should not change. if (balance > 0 && curTimestamp < nextDueTime) { return nextDueTime; } revert("Error: could not calculate next due time."); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter) internal view returns (bool) { uint256 underwriterLimit = underwriter.governanceLimit; require(underwriterLimit != 0, "underwriter does not have governance limit"); uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter); uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount); return totalToBeExtended <= underwriterLimit; } function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) { return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit)); } function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) { uint256 creditExtended; uint256 length = underwriter.creditLines.length; for (uint256 i = 0; i < length; i++) { CreditLine cl = CreditLine(underwriter.creditLines[i]); creditExtended = creditExtended.add(cl.limit()); } return creditExtended; } function updateCreditLineAccounting( CreditLine cl, uint256 balance, uint256 interestOwed, uint256 principalOwed ) internal nonReentrant { // subtract cl from total loans outstanding totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance()); cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); // This resets lastFullPaymentTime. These conditions assure that they have // indeed paid off all their interest and they have a real nextDueTime. (ie. creditline isn't pre-drawdown) uint256 nextDueTime = cl.nextDueTime(); if (interestOwed == 0 && nextDueTime != 0) { // If interest was fully paid off, then set the last full payment as the previous due time uint256 mostRecentLastDueTime; if (currentTime() < nextDueTime) { uint256 secondsPerPeriod = cl.paymentPeriodInDays().mul(SECONDS_PER_DAY); mostRecentLastDueTime = nextDueTime.sub(secondsPerPeriod); } else { mostRecentLastDueTime = nextDueTime; } cl.setLastFullPaymentTime(mostRecentLastDueTime); } // Add new amount back to total loans outstanding totalLoansOutstanding = totalLoansOutstanding.add(balance); cl.setTermEndTime(calculateNewTermEndTime(cl, balance)); // pass in balance as a gas optimization cl.setNextDueTime(calculateNextDueTime(cl)); } function getUSDCBalance(address _address) internal view returns (uint256) { return config.getUSDC().balanceOf(_address); } modifier onlyValidCreditLine(address clAddress) { require(creditLines[clAddress] != address(0), "Unknown credit line"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/CreditDesk.sol"; contract TestCreditDesk is CreditDesk { // solhint-disable-next-line modifiers/ensure-modifiers function _setTotalLoansOutstanding(uint256 amount) public { totalLoansOutstanding = amount; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../core/BaseUpgradeablePausable.sol"; import "../core/ConfigHelper.sol"; import "../core/CreditLine.sol"; import "../core/GoldfinchConfig.sol"; import "../../interfaces/IMigrate.sol"; /** * @title V2 Migrator Contract * @notice This is a one-time use contract solely for the purpose of migrating from our V1 * to our V2 architecture. It will be temporarily granted authority from the Goldfinch governance, * and then revokes it's own authority and transfers it back to governance. * @author Goldfinch */ contract V2Migrator is BaseUpgradeablePausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE"); using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; mapping(address => address) public borrowerContracts; event CreditLineMigrated(address indexed owner, address indexed clToMigrate, address newCl, address tranchedPool); function initialize(address owner, address _config) external initializer { require(owner != address(0) && _config != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = GoldfinchConfig(_config); } function migratePhase1(GoldfinchConfig newConfig) external onlyAdmin { pauseEverything(); migrateToNewConfig(newConfig); migrateToSeniorPool(newConfig); } function migrateCreditLines( GoldfinchConfig newConfig, address[][] calldata creditLinesToMigrate, uint256[][] calldata migrationData ) external onlyAdmin { IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress()); IGoldfinchFactory factory = newConfig.getGoldfinchFactory(); for (uint256 i = 0; i < creditLinesToMigrate.length; i++) { address[] calldata clData = creditLinesToMigrate[i]; uint256[] calldata data = migrationData[i]; address clAddress = clData[0]; address owner = clData[1]; address borrowerContract = borrowerContracts[owner]; if (borrowerContract == address(0)) { borrowerContract = factory.createBorrower(owner); borrowerContracts[owner] = borrowerContract; } (address newCl, address pool) = creditDesk.migrateV1CreditLine( clAddress, borrowerContract, data[0], data[1], data[2], data[3], data[4] ); emit CreditLineMigrated(owner, clAddress, newCl, pool); } } function bulkAddToGoList(GoldfinchConfig newConfig, address[] calldata members) external onlyAdmin { newConfig.bulkAddToGoList(members); } function pauseEverything() internal { IMigrate(config.creditDeskAddress()).pause(); IMigrate(config.poolAddress()).pause(); IMigrate(config.fiduAddress()).pause(); } function migrateToNewConfig(GoldfinchConfig newConfig) internal { uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig); config.setAddress(key, address(newConfig)); IMigrate(config.creditDeskAddress()).updateGoldfinchConfig(); IMigrate(config.poolAddress()).updateGoldfinchConfig(); IMigrate(config.fiduAddress()).updateGoldfinchConfig(); IMigrate(config.goldfinchFactoryAddress()).updateGoldfinchConfig(); key = uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds); newConfig.setNumber(key, 24 * 60 * 60); key = uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays); newConfig.setNumber(key, 365); key = uint256(ConfigOptions.Numbers.LeverageRatio); // 1e18 is the LEVERAGE_RATIO_DECIMALS newConfig.setNumber(key, 3 * 1e18); } function upgradeImplementations(GoldfinchConfig _config, address[] calldata newDeployments) public { address newPoolAddress = newDeployments[0]; address newCreditDeskAddress = newDeployments[1]; address newFiduAddress = newDeployments[2]; address newGoldfinchFactoryAddress = newDeployments[3]; bytes memory data; IMigrate pool = IMigrate(_config.poolAddress()); IMigrate creditDesk = IMigrate(_config.creditDeskAddress()); IMigrate fidu = IMigrate(_config.fiduAddress()); IMigrate goldfinchFactory = IMigrate(_config.goldfinchFactoryAddress()); // Upgrade implementations pool.changeImplementation(newPoolAddress, data); creditDesk.changeImplementation(newCreditDeskAddress, data); fidu.changeImplementation(newFiduAddress, data); goldfinchFactory.changeImplementation(newGoldfinchFactoryAddress, data); } function migrateToSeniorPool(GoldfinchConfig newConfig) internal { IMigrate(config.fiduAddress()).grantRole(MINTER_ROLE, newConfig.seniorPoolAddress()); IMigrate(config.poolAddress()).unpause(); IMigrate(newConfig.poolAddress()).migrateToSeniorPool(); } function closeOutMigration(GoldfinchConfig newConfig) external onlyAdmin { IMigrate fidu = IMigrate(newConfig.fiduAddress()); IMigrate creditDesk = IMigrate(newConfig.creditDeskAddress()); IMigrate oldPool = IMigrate(newConfig.poolAddress()); IMigrate goldfinchFactory = IMigrate(newConfig.goldfinchFactoryAddress()); fidu.unpause(); fidu.renounceRole(MINTER_ROLE, address(this)); fidu.renounceRole(OWNER_ROLE, address(this)); fidu.renounceRole(PAUSER_ROLE, address(this)); creditDesk.renounceRole(OWNER_ROLE, address(this)); creditDesk.renounceRole(PAUSER_ROLE, address(this)); oldPool.renounceRole(OWNER_ROLE, address(this)); oldPool.renounceRole(PAUSER_ROLE, address(this)); goldfinchFactory.renounceRole(OWNER_ROLE, address(this)); goldfinchFactory.renounceRole(PAUSER_ROLE, address(this)); config.renounceRole(PAUSER_ROLE, address(this)); config.renounceRole(OWNER_ROLE, address(this)); newConfig.renounceRole(OWNER_ROLE, address(this)); newConfig.renounceRole(PAUSER_ROLE, address(this)); newConfig.renounceRole(GO_LISTER_ROLE, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; abstract contract IMigrate { function pause() public virtual; function unpause() public virtual; function updateGoldfinchConfig() external virtual; function grantRole(bytes32 role, address assignee) external virtual; function renounceRole(bytes32 role, address self) external virtual; // Proxy methods function transferOwnership(address newOwner) external virtual; function changeImplementation(address newImplementation, bytes calldata data) external virtual; function owner() external view virtual returns (address); // CreditDesk function migrateV1CreditLine( address _clToMigrate, address borrower, uint256 termEndTime, uint256 nextDueTime, uint256 interestAccruedAsOf, uint256 lastFullPaymentTime, uint256 totalInterestPaid ) public virtual returns (address, address); // Pool function migrateToSeniorPool() external virtual; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; contract TestPool is Pool { function _getNumShares(uint256 amount) public view returns (uint256) { return getNumShares(amount); } function _usdcMantissa() public pure returns (uint256) { return usdcMantissa(); } function _fiduMantissa() public pure returns (uint256) { return fiduMantissa(); } function _usdcToFidu(uint256 amount) public pure returns (uint256) { return usdcToFidu(amount); } function _setSharePrice(uint256 newSharePrice) public returns (uint256) { sharePrice = newSharePrice; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/Pool.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; contract FakeV2CreditLine is BaseUpgradeablePausable { // Credit line terms address public borrower; address public underwriter; uint256 public limit; uint256 public interestApr; uint256 public paymentPeriodInDays; uint256 public termInDays; uint256 public lateFeeApr; // Accounting variables uint256 public balance; uint256 public interestOwed; uint256 public principalOwed; uint256 public termEndTime; uint256 public nextDueTime; uint256 public interestAccruedAsOf; uint256 public writedownAmount; uint256 public lastFullPaymentTime; function initialize( address owner, address _borrower, address _underwriter, uint256 _limit, uint256 _interestApr, uint256 _paymentPeriodInDays, uint256 _termInDays, uint256 _lateFeeApr ) public initializer { __BaseUpgradeablePausable__init(owner); borrower = _borrower; underwriter = _underwriter; limit = _limit; interestApr = _interestApr; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lateFeeApr = _lateFeeApr; interestAccruedAsOf = block.timestamp; } function anotherNewFunction() external pure returns (uint256) { return 42; } function authorizePool(address) external view onlyAdmin { // no-op return; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./BaseUpgradeablePausable.sol"; import "./ConfigHelper.sol"; import "../../interfaces/IGo.sol"; import "../../interfaces/IUniqueIdentity0612.sol"; contract Go is IGo, BaseUpgradeablePausable { address public override uniqueIdentity; using SafeMath for uint256; GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; GoldfinchConfig public legacyGoList; uint256[11] public allIdTypes; event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize( address owner, GoldfinchConfig _config, address _uniqueIdentity ) public initializer { require( owner != address(0) && address(_config) != address(0) && _uniqueIdentity != address(0), "Owner and config and UniqueIdentity addresses cannot be empty" ); __BaseUpgradeablePausable__init(owner); _performUpgrade(); config = _config; uniqueIdentity = _uniqueIdentity; } function updateGoldfinchConfig() external override onlyAdmin { config = GoldfinchConfig(config.configAddress()); emit GoldfinchConfigUpdated(msg.sender, address(config)); } function performUpgrade() external onlyAdmin { return _performUpgrade(); } function _performUpgrade() internal { allIdTypes[0] = ID_TYPE_0; allIdTypes[1] = ID_TYPE_1; allIdTypes[2] = ID_TYPE_2; allIdTypes[3] = ID_TYPE_3; allIdTypes[4] = ID_TYPE_4; allIdTypes[5] = ID_TYPE_5; allIdTypes[6] = ID_TYPE_6; allIdTypes[7] = ID_TYPE_7; allIdTypes[8] = ID_TYPE_8; allIdTypes[9] = ID_TYPE_9; allIdTypes[10] = ID_TYPE_10; } /** * @notice sets the config that will be used as the source of truth for the go * list instead of the config currently associated. To use the associated config for to list, set the override * to the null address. */ function setLegacyGoList(GoldfinchConfig _legacyGoList) external onlyAdmin { legacyGoList = _legacyGoList; } /** * @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol * for any of the UID token types. * This status is defined as: whether `balanceOf(account, id)` on the UniqueIdentity * contract is non-zero (where `id` is a supported token id on UniqueIdentity), falling back to the * account's status on the legacy go-list maintained on GoldfinchConfig. * @param account The account whose go status to obtain * @return The account's go status */ function go(address account) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); if (_getLegacyGoList().goList(account) || IUniqueIdentity0612(uniqueIdentity).balanceOf(account, ID_TYPE_0) > 0) { return true; } // start loop at index 1 because we checked index 0 above for (uint256 i = 1; i < allIdTypes.length; ++i) { uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, allIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } /** * @notice Returns whether the provided account is go-listed for use of the Goldfinch protocol * for defined UID token types * @param account The account whose go status to obtain * @param onlyIdTypes Array of id types to check balances * @return The account's go status */ function goOnlyIdTypes(address account, uint256[] memory onlyIdTypes) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); GoldfinchConfig goListSource = _getLegacyGoList(); for (uint256 i = 0; i < onlyIdTypes.length; ++i) { if (onlyIdTypes[i] == ID_TYPE_0 && goListSource.goList(account)) { return true; } uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, onlyIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } /** * @notice Returns whether the provided account is go-listed for use of the SeniorPool on the Goldfinch protocol. * @param account The account whose go status to obtain * @return The account's go status */ function goSeniorPool(address account) public view override returns (bool) { require(account != address(0), "Zero address is not go-listed"); if (account == config.stakingRewardsAddress() || _getLegacyGoList().goList(account)) { return true; } uint256[2] memory seniorPoolIdTypes = [ID_TYPE_0, ID_TYPE_1]; for (uint256 i = 0; i < seniorPoolIdTypes.length; ++i) { uint256 idTypeBalance = IUniqueIdentity0612(uniqueIdentity).balanceOf(account, seniorPoolIdTypes[i]); if (idTypeBalance > 0) { return true; } } return false; } function _getLegacyGoList() internal view returns (GoldfinchConfig) { return address(legacyGoList) == address(0) ? config : legacyGoList; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @dev This interface provides a subset of the functionality of the IUniqueIdentity /// interface -- namely, the subset of functionality needed by Goldfinch protocol contracts /// compiled with Solidity version 0.6.12. interface IUniqueIdentity0612 { function balanceOf(address account, uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/GoldfinchConfig.sol"; contract TestTheConfig { address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE; address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6; address public goldfinchFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9; address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96; address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4; address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5; address public trustedForwarderAddress = 0x956868751Cc565507B3B58E53a6f9f41B56bed74; address public cUSDCAddress = 0x5B281A6DdA0B271e91ae35DE655Ad301C976edb1; address public goldfinchConfigAddress = address(8); function testTheEnums(address configAddress) public { GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds), 8); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays), 9); GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LeverageRatio), 10); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress); GoldfinchConfig(configAddress).setAddress( uint256(ConfigOptions.Addresses.GoldfinchFactory), goldfinchFactoryAddress ); GoldfinchConfig(configAddress).setAddress( uint256(ConfigOptions.Addresses.TrustedForwarder), trustedForwarderAddress ); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CUSDCContract), cUSDCAddress); GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig), goldfinchConfigAddress); GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../protocol/core/GoldfinchConfig.sol"; contract TestGoldfinchConfig is GoldfinchConfig { function setAddressForTest(uint256 addressKey, address newAddress) public { addresses[addressKey] = newAddress; } }
This supports withdrawing before or after locking because principal share price starts at 1 and is set to 0 on lock. Interest share price is always 0 until interest payments come back, when it increases The principalAmount is used as the totalShares because we want the interestSharePrice to be expressed as a percent of total loan value e.g. if the interest is 10% APR, the interestSharePrice should approach a max of 0.1.
function redeemableInterestAndPrincipal(TrancheInfo storage trancheInfo, IPoolTokens.TokenInfo memory tokenInfo) internal view returns (uint256 interestRedeemable, uint256 principalRedeemable) { uint256 maxPrincipalRedeemable = sharePriceToUsdc(trancheInfo.principalSharePrice, tokenInfo.principalAmount); uint256 maxInterestRedeemable = sharePriceToUsdc(trancheInfo.interestSharePrice, tokenInfo.principalAmount); interestRedeemable = maxInterestRedeemable.sub(tokenInfo.interestRedeemed); principalRedeemable = maxPrincipalRedeemable.sub(tokenInfo.principalRedeemed); return (interestRedeemable, principalRedeemable); }
6,235,142
[ 1, 2503, 6146, 598, 9446, 310, 1865, 578, 1839, 18887, 2724, 8897, 7433, 6205, 2542, 622, 404, 471, 353, 444, 358, 374, 603, 2176, 18, 5294, 395, 7433, 6205, 353, 3712, 374, 3180, 16513, 25754, 12404, 1473, 16, 1347, 518, 7033, 3304, 1021, 8897, 6275, 353, 1399, 487, 326, 2078, 24051, 2724, 732, 2545, 326, 16513, 9535, 5147, 358, 506, 26863, 487, 279, 5551, 434, 2078, 28183, 460, 425, 18, 75, 18, 309, 326, 16513, 353, 1728, 9, 432, 8025, 16, 326, 16513, 9535, 5147, 1410, 17504, 279, 943, 434, 374, 18, 21, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 283, 24903, 429, 29281, 1876, 9155, 12, 17730, 18706, 966, 2502, 13637, 18706, 966, 16, 467, 2864, 5157, 18, 1345, 966, 3778, 1147, 966, 13, 203, 565, 2713, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 16513, 426, 24903, 429, 16, 2254, 5034, 8897, 426, 24903, 429, 13, 203, 225, 288, 203, 565, 2254, 5034, 943, 9155, 426, 24903, 429, 273, 7433, 5147, 774, 3477, 7201, 12, 13171, 18706, 966, 18, 26138, 9535, 5147, 16, 1147, 966, 18, 26138, 6275, 1769, 203, 565, 2254, 5034, 943, 29281, 426, 24903, 429, 273, 7433, 5147, 774, 3477, 7201, 12, 13171, 18706, 966, 18, 2761, 395, 9535, 5147, 16, 1147, 966, 18, 26138, 6275, 1769, 203, 203, 565, 16513, 426, 24903, 429, 273, 943, 29281, 426, 24903, 429, 18, 1717, 12, 2316, 966, 18, 2761, 395, 426, 24903, 329, 1769, 203, 565, 8897, 426, 24903, 429, 273, 943, 9155, 426, 24903, 429, 18, 1717, 12, 2316, 966, 18, 26138, 426, 24903, 329, 1769, 203, 203, 565, 327, 261, 2761, 395, 426, 24903, 429, 16, 8897, 426, 24903, 429, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x16E13cd27463f45F867A2C4091eb9EA17EdBF6e8/sources/browser/Election.sol
* Function to tranfer 'Vote token' to 'Voter balance' and change Voter 'authorize' status to 'true'/send 1 token to voter address
function authorizeVoter(address _voterAddress) public onlyOwner { transfer(_voterAddress, 1); remainingVotes = totalVotes.sub(1); voterList[_voterAddress].authorize = true; }
8,168,958
[ 1, 2083, 358, 13637, 586, 296, 19338, 1147, 11, 358, 296, 58, 20005, 11013, 11, 471, 2549, 776, 20005, 296, 22488, 11, 1267, 358, 296, 3767, 11, 19, 4661, 404, 1147, 358, 331, 20005, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 12229, 58, 20005, 12, 2867, 389, 90, 20005, 1887, 13, 1071, 1338, 5541, 288, 203, 5411, 7412, 24899, 90, 20005, 1887, 16, 404, 1769, 203, 5411, 4463, 29637, 273, 2078, 29637, 18, 1717, 12, 21, 1769, 203, 5411, 331, 20005, 682, 63, 67, 90, 20005, 1887, 8009, 22488, 273, 638, 31, 203, 3639, 289, 203, 540, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x66938285B15da67A93D80D08f8f2DA665449F08d/sources/contracts/AXLPresale.sol
On presale failure Percentile withdrawls allows fee on transfer or rebasing tokens to still work Refund return;
function userWithdrawBaseTokens () public nonReentrant { BuyerInfo storage buyer = buyers[msg.sender]; uint256 remainingBaseBalance = address(this).balance; require(remainingBaseBalance >= buyer.base, "Nothing to withdraw."); status.base_withdraw = status.base_withdraw.add(buyer.base); address payable reciver = payable(msg.sender); reciver.transfer(buyer.base); if(msg.sender == owner) { ownerWithdrawTokens(); } buyer.base = 0; buyer.sale = 0; emit UserWithdrawSuccess(buyer.base);
4,929,527
[ 1, 1398, 4075, 5349, 5166, 21198, 398, 598, 9446, 3251, 5360, 14036, 603, 7412, 578, 283, 9157, 310, 2430, 358, 4859, 1440, 3941, 1074, 327, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 729, 1190, 9446, 2171, 5157, 1832, 1071, 1661, 426, 8230, 970, 288, 203, 540, 203, 3639, 605, 16213, 966, 2502, 27037, 273, 30143, 414, 63, 3576, 18, 15330, 15533, 203, 540, 203, 3639, 2254, 5034, 4463, 2171, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 540, 203, 3639, 2583, 12, 17956, 2171, 13937, 1545, 27037, 18, 1969, 16, 315, 23814, 358, 598, 9446, 1199, 1769, 203, 203, 3639, 1267, 18, 1969, 67, 1918, 9446, 273, 1267, 18, 1969, 67, 1918, 9446, 18, 1289, 12, 70, 16213, 18, 1969, 1769, 203, 540, 203, 3639, 1758, 8843, 429, 1950, 1667, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 1950, 1667, 18, 13866, 12, 70, 16213, 18, 1969, 1769, 203, 203, 3639, 309, 12, 3576, 18, 15330, 422, 3410, 13, 288, 203, 5411, 3410, 1190, 9446, 5157, 5621, 203, 3639, 289, 203, 203, 3639, 27037, 18, 1969, 273, 374, 31, 203, 3639, 27037, 18, 87, 5349, 273, 374, 31, 203, 540, 203, 3639, 3626, 2177, 1190, 9446, 4510, 12, 70, 16213, 18, 1969, 1769, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/56/0x65f714E8d8b21bD597Ec229e13F0D96D2B4C2093/sources/contracts/MTCRewardContract_v1.sol
Check available amount Transfer tokens to the user
function withdrawReward(uint256 _amount) external nonReentrant { address account = msg.sender; require(_amount > 0, "Amount must be greater than zero."); uint256 accountBalance = acceptedToken.allowance(address(this), account); require(accountBalance >= _amount, "Insufficient balance for withdrawal."); acceptedToken.safeTransferFrom(address(this), account, _amount); acceptedToken.safeDecreaseAllowance(account, _amount); }
3,249,378
[ 1, 1564, 2319, 3844, 12279, 2430, 358, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 17631, 1060, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 1758, 2236, 273, 1234, 18, 15330, 31, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 6275, 1297, 506, 6802, 2353, 3634, 1199, 1769, 203, 203, 3639, 2254, 5034, 2236, 13937, 273, 8494, 1345, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 2236, 1769, 203, 3639, 2583, 12, 4631, 13937, 1545, 389, 8949, 16, 315, 5048, 11339, 11013, 364, 598, 9446, 287, 1199, 1769, 203, 203, 3639, 8494, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 2236, 16, 389, 8949, 1769, 203, 3639, 8494, 1345, 18, 4626, 23326, 448, 7009, 1359, 12, 4631, 16, 389, 8949, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-15 */ // File: contracts/NFTMint.sol pragma solidity ^0.5.0; 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'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 Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () public{ address msgSender = msg.sender; _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() == msg.sender, "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 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) internal onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract NFTBANK721 is Ownable{ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed from, address indexed to, uint256 indexed tokenId); // Token name string private _name; uint256 public tokenCount; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) public _owners; // Mapping owner address to token count mapping (address => uint256) public _balances; // Mapping from token ID to approved address mapping (uint256 => address) public _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; mapping (uint256 => string) private _tokenURIs; mapping (uint256 => address) public _creator; constructor (string memory name_, string memory symbol_) public{ _name = name_; _symbol = symbol_; } function _transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); transferOwnership(newOwner); } function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function _exists(uint256 tokenId) internal view returns (bool) { return _owners[tokenId] != address(0); } function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function _approve(address to, uint256 tokenId) public onlyOwner{ _tokenApprovals[tokenId] = to; } function _mint(address to, uint256 tokenId,string memory _tokenuri) public onlyOwner{ require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _balances[to] += 1; _owners[tokenId] = to; _creator[tokenId] = to; _setTokenURI(tokenId, _tokenuri); tokenCount++; emit Transfer(address(0), to, tokenId); } function setApprovalForAll(address from, address to, bool approved, uint256 tokenId) public onlyOwner{ require(to == msg.sender, "ERC721: approve to caller"); _approve(to, tokenId); _operatorApprovals[from][to] = approved; emit Approval(from, to, tokenId); } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal onlyOwner{ require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } function tokenTransfer(address from, address to, uint256 tokenId) public onlyOwner{ _transfer(from, to, tokenId); } function _transfer(address from, address to, uint256 tokenId) public onlyOwner{ require(to != address(0), "ERC721: transfer to the zero address"); require(_operatorApprovals[_creator[tokenId]][owner()] == true , "Need operator approval for 3rd party transfers."); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _burn(uint256 tokenId, address from, address admin) public onlyOwner{ require(_owners[tokenId] == from || from == owner(), "Only Burn Allowed Token Owner or Admin"); require(_operatorApprovals[_creator[tokenId]][admin] == true, "Need operator approval for 3rd party burns."); // // Clear approvals _approve(address(0), tokenId); _operatorApprovals[_creator[tokenId]][admin] = false; _balances[_owners[tokenId]] -= 1; delete _owners[tokenId]; delete _creator[tokenId]; emit Transfer(from, address(0), tokenId); } } contract NFTMint is NFTBANK721{ mapping(string => bool) _nameexits; // uint256 public tokenCount; constructor( string memory name, string memory symbol ) NFTBANK721(name, symbol) public{ } }
uint256 public tokenCount;
contract NFTMint is NFTBANK721{ mapping(string => bool) _nameexits; constructor( string memory name, string memory symbol ) NFTBANK721(name, symbol) public{ } }
10,773,303
[ 1, 11890, 5034, 1071, 1147, 1380, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 4464, 49, 474, 353, 423, 4464, 38, 20201, 27, 5340, 95, 203, 377, 2874, 12, 1080, 516, 1426, 13, 389, 529, 338, 1282, 31, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 203, 565, 262, 423, 4464, 38, 20201, 27, 5340, 12, 529, 16, 3273, 13, 1071, 95, 203, 4202, 203, 565, 289, 1377, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** * @title NATEE WARRANT 01 ERC20 token * * @dev NATEE WARRANT 01 use for airdrop bonus and other for NATEE Token * User can transfer to NATEE Token by pay at FIX RATE * if user hold NATEE WARRANT until expride FEE to change will reduce to 0 */ library SafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if(a==0 || b==0) return 0; uint256 c = a * b; require(a == 0 || 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 sub(uint256 a, uint256 b) internal pure returns (uint256) { require( b<= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // Only Owner modifier it support a lot owner but finally should have 1 owner contract Ownable { mapping (address=>bool) owners; address owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AddOwner(address newOwner); event RemoveOwner(address owner); /** * @dev Ownable constructor ตั้งค่าบัญชีของ sender ให้เป็น `owner` ดั้งเดิมของ contract * */ constructor() public { owner = msg.sender; owners[msg.sender] = true; } function isContract(address _addr) internal view returns(bool){ uint256 length; assembly{ length := extcodesize(_addr) } if(length > 0){ return true; } else { return false; } } // For Single Owner modifier onlyOwner(){ require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner{ require(isContract(newOwner) == false); emit OwnershipTransferred(owner,newOwner); owner = newOwner; } //For multiple Owner modifier onlyOwners(){ require(owners[msg.sender] == true); _; } function addOwner(address newOwner) public onlyOwners{ require(owners[newOwner] == false); require(newOwner != msg.sender); owners[newOwner] = true; emit AddOwner(newOwner); } function removeOwner(address _owner) public onlyOwners{ require(_owner != msg.sender); // can't remove your self owners[_owner] = false; emit RemoveOwner(_owner); } function isOwner(address _owner) public view returns(bool){ return owners[_owner]; } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); function totalSupply() public view returns (uint256); function balanceOf(address tokenOwner) public view returns (uint256 balance); function allowance(address tokenOwner, address spender) public view returns (uint256 remaining); function transfer(address to, uint256 tokens) public returns (bool success); function approve(address spender, uint256 tokens) public returns (bool success); function transferFrom(address from, address to, uint256 tokens) public returns (bool success); } contract StandardERC20 is ERC20{ using SafeMath256 for uint256; mapping (address => uint256) balance; mapping (address => mapping (address=>uint256)) allowed; uint256 totalSupply_; event Transfer(address indexed from,address indexed to,uint256 value); event Approval(address indexed owner,address indexed spender,uint256 value); function totalSupply() public view returns (uint256){ return totalSupply_; } function balanceOf(address _walletAddress) public view returns (uint256){ return balance[_walletAddress]; } function allowance(address _owner, address _spender) public view returns (uint256){ return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool){ require(_value <= balance[msg.sender]); require(_to != address(0)); balance[msg.sender] = balance[msg.sender].sub(_value); balance[_to] = balance[_to].add(_value); emit Transfer(msg.sender,_to,_value); return true; } function approve(address _spender, uint256 _value) public returns (bool){ allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool){ require(_value <= balance[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balance[_from] = balance[_from].sub(_value); balance[_to] = balance[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } } contract SGDSInterface{ function balanceOf(address tokenOwner) public view returns (uint256 balance); function intTransfer(address _from, address _to, uint256 _value) external; function transferWallet(address _from,address _to) external; function getCanControl(address _addr) external view returns(bool); // if true mean user can control by him. false mean Company can control function useSGDS(address useAddr,uint256 value) external returns(bool); } contract NATEE_WARRANT is StandardERC20, Ownable { using SafeMath256 for uint256; string public name = "NATEE WARRANT"; string public symbol = "NATEE-W1"; // Real Name NATEE uint256 public decimals = 18; uint256 public INITIAL_SUPPLY = 20000000 ether; uint256 public totalUndist; // How many warrant that not distributed uint256 public totalRedeem; address public NATEE_CONTRACT = address(0); uint256 public transFee = 100; uint32 public expireDate; SGDSInterface public sgds; event RedeemWarrant(address indexed addr,uint256 _value); event SetControlToken(address indexed addr, bool outControl); event FeeTransfer(address indexed addr,uint256 _value); event TransferWallet(address indexed from,address indexed to,address indexed execute_); mapping(address => bool) userControl; constructor() public { totalSupply_ = INITIAL_SUPPLY; totalUndist = INITIAL_SUPPLY; expireDate = uint32(now + 1825 days); // Start 5 Year Expire First sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89); } function setExpireDate(uint32 newDate) external onlyOwners{ if(newDate < expireDate && newDate > uint32(now)) { expireDate = newDate; } } function sendWarrant(address _to,uint256 _value) external onlyOwners { require(_value <= totalUndist); balance[_to] += _value; totalUndist -= _value; emit Transfer(address(this),_to,_value); } // This for use seitee transfer . Seitee will pay for gas function intTransfer(address _from, address _to, uint256 _value) external onlyOwners{ require(userControl[_from] == false); // Company can do if they still allow compay to do it require(balance[_from] >= _value); //require(_to != address(0)); // internal Call then can remove this balance[_from] -= _value; balance[_to] += _value; emit Transfer(_from,_to,_value); } // THIS IS SOS FUNCTION // For transfer all Warrant Token to new Wallet Address. Want to pay 1 SGDS for fee. function transferWallet(address _from,address _to) external onlyOwners{ require(userControl[_from] == false); require(sgds.getCanControl(_from) == false); require(sgds.balanceOf(_from) >= transFee); uint256 value = balance[_from]; balance[_from] = balance[_from].sub(value); balance[_to] = balance[_to].add(value); // sub with FEE sgds.useSGDS(_from,transFee); emit TransferWallet(_from,_to,msg.sender); emit Transfer(_from,_to,value); } // This function will call direct from Natee Contract To deduct Warrant function redeemWarrant(address _from, uint256 _value) external { require(msg.sender == NATEE_CONTRACT); require(balance[_from] >= _value); balance[_from] = balance[_from].sub(_value); totalSupply_ -= _value; totalRedeem += _value; emit Transfer(_from,address(0),_value); emit RedeemWarrant(_from,_value); } // Address Owner can set permision by him self. Set to true will stop company control his/her wallet function setUserControl(bool _control) public { userControl[msg.sender] = _control; emit SetControlToken(msg.sender,_control); } function getUserControl(address _addr) external view returns(bool){ return userControl[_addr]; } // This function can set 1 time to make sure no one can cheat function setNateeContract(address addr) onlyOwners external{ require(NATEE_CONTRACT == address(0)); NATEE_CONTRACT = addr; } function setTransFee(uint256 _fee) onlyOwners public{ transFee = _fee; } }
Start 5 Year Expire First
expireDate = uint32(now + 1825 days);
14,042,878
[ 1, 1685, 1381, 16666, 7784, 577, 5783, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6930, 1626, 273, 2254, 1578, 12, 3338, 397, 6549, 2947, 4681, 1769, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: Issuer.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/Issuer.sol * Docs: https://docs.synthetix.io/contracts/Issuer * * Contract Dependencies: * - IAddressResolver * - IIssuer * - MixinResolver * - MixinSystemSettings * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 Synthetix * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.synthetix.io/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal} constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } // Computes `a - b`, setting the value to 0 if b > a. function floorsub(uint a, uint b) internal pure returns (uint) { return b >= a ? 0 : a - b; } } interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/ifeepool interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } // https://docs.synthetix.io/contracts/source/interfaces/isynthetixstate interface ISynthetixState { // Views function debtLedger(uint index) external view returns (uint); function issuanceData(address account) external view returns (uint initialDebtOwnership, uint debtEntryIndex); function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function lastDebtLedgerEntry() external view returns (uint); // Mutative functions function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } // https://docs.synthetix.io/contracts/source/interfaces/idelegateapprovals interface IDelegateApprovals { // Views function canBurnFor(address authoriser, address delegate) external view returns (bool); function canIssueFor(address authoriser, address delegate) external view returns (bool); function canClaimFor(address authoriser, address delegate) external view returns (bool); function canExchangeFor(address authoriser, address delegate) external view returns (bool); // Mutative function approveAllDelegatePowers(address delegate) external; function removeAllDelegatePowers(address delegate) external; function approveBurnOnBehalf(address delegate) external; function removeBurnOnBehalf(address delegate) external; function approveIssueOnBehalf(address delegate) external; function removeIssueOnBehalf(address delegate) external; function approveClaimOnBehalf(address delegate) external; function removeClaimOnBehalf(address delegate) external; function approveExchangeOnBehalf(address delegate) external; function removeExchangeOnBehalf(address delegate) external; } // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // https://docs.synthetix.io/contracts/source/interfaces/iethercollateral interface IEtherCollateral { // Views function totalIssuedSynths() external view returns (uint256); function totalLoansCreated() external view returns (uint256); function totalOpenLoanCount() external view returns (uint256); // Mutative functions function openLoan() external payable returns (uint256 loanID); function closeLoan(uint256 loanID) external; function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external; } // https://docs.synthetix.io/contracts/source/interfaces/iethercollateralsusd interface IEtherCollateralsUSD { // Views function totalIssuedSynths() external view returns (uint256); function totalLoansCreated() external view returns (uint256); function totalOpenLoanCount() external view returns (uint256); // Mutative functions function openLoan(uint256 _loanAmount) external payable returns (uint256 loanID); function closeLoan(uint256 loanID) external; function liquidateUnclosedLoan(address _loanCreatorsAddress, uint256 _loanID) external; function depositCollateral(address account, uint256 loanID) external payable; function withdrawCollateral(uint256 loanID, uint256 withdrawAmount) external; function repayLoan( address _loanCreatorsAddress, uint256 _loanID, uint256 _repayAmount ) external; } // https://docs.synthetix.io/contracts/source/interfaces/ihasbalance interface IHasBalance { // Views function balanceOf(address account) external view returns (uint); } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.synthetix.io/contracts/source/interfaces/iliquidations interface ILiquidations { // Views function isOpenForLiquidation(address account) external view returns (bool); function getLiquidationDeadlineForAccount(address account) external view returns (uint); function isLiquidationDeadlinePassed(address account) external view returns (bool); function liquidationDelay() external view returns (uint); function liquidationRatio() external view returns (uint); function liquidationPenalty() external view returns (uint); function calculateAmountToFixCollateral(uint debtBalance, uint collateral) external view returns (uint); // Mutative Functions function flagAccountForLiquidation(address account) external; // Restricted: used internally to Synthetix function removeAccountInLiquidation(address account) external; function checkAndRemoveAccountInLiquidation(address account) external; } interface ICollateralManager { // Manager information function hasCollateral(address collateral) external view returns (bool); function isSynthManaged(bytes32 currencyKey) external view returns (bool); // State information function long(bytes32 synth) external view returns (uint amount); function short(bytes32 synth) external view returns (uint amount); function totalLong() external view returns (uint susdValue, bool anyRateIsInvalid); function totalShort() external view returns (uint susdValue, bool anyRateIsInvalid); function getBorrowRate() external view returns (uint borrowRate, bool anyRateIsInvalid); function getShortRate(bytes32 synth) external view returns (uint shortRate, bool rateIsInvalid); function getRatesAndTime(uint index) external view returns ( uint entryRate, uint lastRate, uint lastUpdated, uint newIndex ); function getShortRatesAndTime(bytes32 currency, uint index) external view returns ( uint entryRate, uint lastRate, uint lastUpdated, uint newIndex ); function exceedsDebtLimit(uint amount, bytes32 currency) external view returns (bool canIssue, bool anyRateIsInvalid); function areSynthsAndCurrenciesSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external view returns (bool); function areShortableSynthsSet(bytes32[] calldata requiredSynthNamesInResolver, bytes32[] calldata synthKeys) external view returns (bool); // Loans function getNewLoanId() external returns (uint id); // Manager mutative function addCollaterals(address[] calldata collaterals) external; function removeCollaterals(address[] calldata collaterals) external; function addSynths(bytes32[] calldata synthNamesInResolver, bytes32[] calldata synthKeys) external; function removeSynths(bytes32[] calldata synths, bytes32[] calldata synthKeys) external; function addShortableSynths(bytes32[2][] calldata requiredSynthAndInverseNamesInResolver, bytes32[] calldata synthKeys) external; function removeShortableSynths(bytes32[] calldata synths) external; // State mutative function updateBorrowRates(uint rate) external; function updateShortRates(bytes32 currency, uint rate) external; function incrementLongs(bytes32 synth, uint amount) external; function decrementLongs(bytes32 synth, uint amount) external; function incrementShorts(bytes32 synth, uint amount) external; function decrementShorts(bytes32 synth, uint amount) external; } // Inheritance // Libraries // Internal references interface IRewardEscrowV2 { // Views function balanceOf(address account) external view returns (uint); } interface IIssuerInternalDebtCache { function updateCachedSynthDebtWithRate(bytes32 currencyKey, uint currencyRate) external; function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external; function updateDebtCacheValidity(bool currentlyInvalid) external; function totalNonSnxBackedDebt() external view returns (uint excludedDebt, bool isInvalid); function cacheInfo() external view returns ( uint cachedDebt, uint timestamp, bool isInvalid, bool isStale ); } // https://docs.synthetix.io/contracts/source/contracts/issuer contract Issuer is Owned, MixinSystemSettings, IIssuer { using SafeMath for uint; using SafeDecimalMath for uint; // Available Synths which can be used with the system ISynth[] public availableSynths; mapping(bytes32 => ISynth) public synths; mapping(address => bytes32) public synthsByAddress; /* ========== ENCODED NAMES ========== */ bytes32 internal constant sUSD = "sUSD"; bytes32 internal constant sETH = "sETH"; bytes32 internal constant SNX = "SNX"; // Flexible storage names bytes32 public constant CONTRACT_NAME = "Issuer"; bytes32 internal constant LAST_ISSUE_EVENT = "lastIssueEvent"; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral"; bytes32 private constant CONTRACT_ETHERCOLLATERAL_SUSD = "EtherCollateralsUSD"; bytes32 private constant CONTRACT_COLLATERALMANAGER = "CollateralManager"; bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2"; bytes32 private constant CONTRACT_SYNTHETIXESCROW = "SynthetixEscrow"; bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations"; bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache"; constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](13); newAddresses[0] = CONTRACT_SYNTHETIX; newAddresses[1] = CONTRACT_EXCHANGER; newAddresses[2] = CONTRACT_EXRATES; newAddresses[3] = CONTRACT_SYNTHETIXSTATE; newAddresses[4] = CONTRACT_FEEPOOL; newAddresses[5] = CONTRACT_DELEGATEAPPROVALS; newAddresses[6] = CONTRACT_ETHERCOLLATERAL; newAddresses[7] = CONTRACT_ETHERCOLLATERAL_SUSD; newAddresses[8] = CONTRACT_REWARDESCROW_V2; newAddresses[9] = CONTRACT_SYNTHETIXESCROW; newAddresses[10] = CONTRACT_LIQUIDATIONS; newAddresses[11] = CONTRACT_DEBTCACHE; newAddresses[12] = CONTRACT_COLLATERALMANAGER; return combineArrays(existingAddresses, newAddresses); } function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function synthetixState() internal view returns (ISynthetixState) { return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function liquidations() internal view returns (ILiquidations) { return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS)); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS)); } function etherCollateral() internal view returns (IEtherCollateral) { return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL)); } function etherCollateralsUSD() internal view returns (IEtherCollateralsUSD) { return IEtherCollateralsUSD(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL_SUSD)); } function collateralManager() internal view returns (ICollateralManager) { return ICollateralManager(requireAndGetAddress(CONTRACT_COLLATERALMANAGER)); } function rewardEscrowV2() internal view returns (IRewardEscrowV2) { return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2)); } function synthetixEscrow() internal view returns (IHasBalance) { return IHasBalance(requireAndGetAddress(CONTRACT_SYNTHETIXESCROW)); } function debtCache() internal view returns (IIssuerInternalDebtCache) { return IIssuerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE)); } function issuanceRatio() external view returns (uint) { return getIssuanceRatio(); } function _availableCurrencyKeysWithOptionalSNX(bool withSNX) internal view returns (bytes32[] memory) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length + (withSNX ? 1 : 0)); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[address(availableSynths[i])]; } if (withSNX) { currencyKeys[availableSynths.length] = SNX; } return currencyKeys; } // Returns the total value of the debt pool in currency specified by `currencyKey`. // To return only the SNX-backed debt, set `excludeCollateral` to true. function _totalIssuedSynths(bytes32 currencyKey, bool excludeCollateral) internal view returns (uint totalIssued, bool anyRateIsInvalid) { (uint debt, , bool cacheIsInvalid, bool cacheIsStale) = debtCache().cacheInfo(); anyRateIsInvalid = cacheIsInvalid || cacheIsStale; IExchangeRates exRates = exchangeRates(); // Add total issued synths from non snx collateral back into the total if not excluded if (!excludeCollateral) { (uint nonSnxDebt, bool invalid) = debtCache().totalNonSnxBackedDebt(); debt = debt.add(nonSnxDebt); anyRateIsInvalid = anyRateIsInvalid || invalid; } if (currencyKey == sUSD) { return (debt, anyRateIsInvalid); } (uint currencyRate, bool currencyRateInvalid) = exRates.rateAndInvalid(currencyKey); return (debt.divideDecimalRound(currencyRate), anyRateIsInvalid || currencyRateInvalid); } function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey) internal view returns ( uint debtBalance, uint totalSystemValue, bool anyRateIsInvalid ) { ISynthetixState state = synthetixState(); // What was their initial debt ownership? (uint initialDebtOwnership, uint debtEntryIndex) = state.issuanceData(_issuer); // What's the total value of the system excluding ETH backed synths in their requested currency? (totalSystemValue, anyRateIsInvalid) = _totalIssuedSynths(currencyKey, true); // If it's zero, they haven't issued, and they have no debt. // Note: it's more gas intensive to put this check here rather than before _totalIssuedSynths // if they have 0 SNX, but it's a necessary trade-off if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsInvalid); // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = state .lastDebtLedgerEntry() .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise(currentDebtOwnership); // Convert back into 18 decimals (1e18) debtBalance = highPrecisionBalance.preciseDecimalToDecimal(); } function _canBurnSynths(address account) internal view returns (bool) { return now >= _lastIssueEvent(account).add(getMinimumStakeTime()); } function _lastIssueEvent(address account) internal view returns (uint) { // Get the timestamp of the last issue this account made return flexibleStorage().getUIntValue(CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account))); } function _remainingIssuableSynths(address _issuer) internal view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt, bool anyRateIsInvalid ) { (alreadyIssued, totalSystemDebt, anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, sUSD); (uint issuable, bool isInvalid) = _maxIssuableSynths(_issuer); maxIssuable = issuable; anyRateIsInvalid = anyRateIsInvalid || isInvalid; if (alreadyIssued >= maxIssuable) { maxIssuable = 0; } else { maxIssuable = maxIssuable.sub(alreadyIssued); } } function _snxToUSD(uint amount, uint snxRate) internal pure returns (uint) { return amount.multiplyDecimalRound(snxRate); } function _usdToSnx(uint amount, uint snxRate) internal pure returns (uint) { return amount.divideDecimalRound(snxRate); } function _maxIssuableSynths(address _issuer) internal view returns (uint, bool) { // What is the value of their SNX balance in sUSD (uint snxRate, bool isInvalid) = exchangeRates().rateAndInvalid(SNX); uint destinationValue = _snxToUSD(_collateral(_issuer), snxRate); // They're allowed to issue up to issuanceRatio of that value return (destinationValue.multiplyDecimal(getIssuanceRatio()), isInvalid); } function _collateralisationRatio(address _issuer) internal view returns (uint, bool) { uint totalOwnedSynthetix = _collateral(_issuer); (uint debtBalance, , bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(_issuer, SNX); // it's more gas intensive to put this check here if they have 0 SNX, but it complies with the interface if (totalOwnedSynthetix == 0) return (0, anyRateIsInvalid); return (debtBalance.divideDecimalRound(totalOwnedSynthetix), anyRateIsInvalid); } function _collateral(address account) internal view returns (uint) { uint balance = IERC20(address(synthetix())).balanceOf(account); if (address(synthetixEscrow()) != address(0)) { balance = balance.add(synthetixEscrow().balanceOf(account)); } if (address(rewardEscrowV2()) != address(0)) { balance = balance.add(rewardEscrowV2().balanceOf(account)); } return balance; } function minimumStakeTime() external view returns (uint) { return getMinimumStakeTime(); } function canBurnSynths(address account) external view returns (bool) { return _canBurnSynths(account); } function availableCurrencyKeys() external view returns (bytes32[] memory) { return _availableCurrencyKeysWithOptionalSNX(false); } function availableSynthCount() external view returns (uint) { return availableSynths.length; } function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid) { (, anyRateInvalid) = exchangeRates().ratesAndInvalidForCurrencies(_availableCurrencyKeysWithOptionalSNX(true)); } function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) { (totalIssued, ) = _totalIssuedSynths(currencyKey, excludeEtherCollateral); } function lastIssueEvent(address account) external view returns (uint) { return _lastIssueEvent(account); } function collateralisationRatio(address _issuer) external view returns (uint cratio) { (cratio, ) = _collateralisationRatio(_issuer); } function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid) { return _collateralisationRatio(_issuer); } function collateral(address account) external view returns (uint) { return _collateral(account); } function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) { ISynthetixState state = synthetixState(); // What was their initial debt ownership? (uint initialDebtOwnership, ) = state.issuanceData(_issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; (debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey); } function remainingIssuableSynths(address _issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ) { (maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuableSynths(_issuer); } function maxIssuableSynths(address _issuer) external view returns (uint) { (uint maxIssuable, ) = _maxIssuableSynths(_issuer); return maxIssuable; } function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint debtBalance; (debtBalance, , anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, SNX); uint lockedSynthetixValue = debtBalance.divideDecimalRound(getIssuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { transferable = 0; } else { transferable = balance.sub(lockedSynthetixValue); } } function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory) { uint numKeys = currencyKeys.length; ISynth[] memory addresses = new ISynth[](numKeys); for (uint i = 0; i < numKeys; i++) { addresses[i] = synths[currencyKeys[i]]; } return addresses; } /* ========== MUTATIVE FUNCTIONS ========== */ function _addSynth(ISynth synth) internal { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == ISynth(0), "Synth exists"); require(synthsByAddress[address(synth)] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[address(synth)] = currencyKey; emit SynthAdded(currencyKey, address(synth)); } function addSynth(ISynth synth) external onlyOwner { _addSynth(synth); // Invalidate the cache to force a snapshot to be recomputed. If a synth were to be added // back to the system and it still somehow had cached debt, this would force the value to be // updated. debtCache().updateDebtCacheValidity(true); } function addSynths(ISynth[] calldata synthsToAdd) external onlyOwner { uint numSynths = synthsToAdd.length; for (uint i = 0; i < numSynths; i++) { _addSynth(synthsToAdd[i]); } // Invalidate the cache to force a snapshot to be recomputed. debtCache().updateDebtCacheValidity(true); } function _removeSynth(bytes32 currencyKey) internal { address synthToRemove = address(synths[currencyKey]); require(synthToRemove != address(0), "Synth does not exist"); require(IERC20(synthToRemove).totalSupply() == 0, "Synth supply exists"); require(currencyKey != sUSD, "Cannot remove synth"); // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (address(availableSynths[i]) == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[synthToRemove]; delete synths[currencyKey]; emit SynthRemoved(currencyKey, synthToRemove); } function removeSynth(bytes32 currencyKey) external onlyOwner { // Remove its contribution from the debt pool snapshot, and // invalidate the cache to force a new snapshot. IIssuerInternalDebtCache cache = debtCache(); cache.updateCachedSynthDebtWithRate(currencyKey, 0); cache.updateDebtCacheValidity(true); _removeSynth(currencyKey); } function removeSynths(bytes32[] calldata currencyKeys) external onlyOwner { uint numKeys = currencyKeys.length; // Remove their contributions from the debt pool snapshot, and // invalidate the cache to force a new snapshot. IIssuerInternalDebtCache cache = debtCache(); uint[] memory zeroRates = new uint[](numKeys); cache.updateCachedSynthDebtsWithRates(currencyKeys, zeroRates); cache.updateDebtCacheValidity(true); for (uint i = 0; i < numKeys; i++) { _removeSynth(currencyKeys[i]); } } function issueSynths(address from, uint amount) external onlySynthetix { _issueSynths(from, amount, false); } function issueMaxSynths(address from) external onlySynthetix { _issueSynths(from, 0, true); } function issueSynthsOnBehalf( address issueForAddress, address from, uint amount ) external onlySynthetix { _requireCanIssueOnBehalf(issueForAddress, from); _issueSynths(issueForAddress, amount, false); } function issueMaxSynthsOnBehalf(address issueForAddress, address from) external onlySynthetix { _requireCanIssueOnBehalf(issueForAddress, from); _issueSynths(issueForAddress, 0, true); } function burnSynths(address from, uint amount) external onlySynthetix { _voluntaryBurnSynths(from, amount, false); } function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external onlySynthetix { _requireCanBurnOnBehalf(burnForAddress, from); _voluntaryBurnSynths(burnForAddress, amount, false); } function burnSynthsToTarget(address from) external onlySynthetix { _voluntaryBurnSynths(from, 0, true); } function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external onlySynthetix { _requireCanBurnOnBehalf(burnForAddress, from); _voluntaryBurnSynths(burnForAddress, 0, true); } function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external onlySynthetix returns (uint totalRedeemed, uint amountToLiquidate) { // Ensure waitingPeriod and sUSD balance is settled as burning impacts the size of debt pool require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, sUSD), "sUSD needs to be settled"); // Check account is liquidation open require(liquidations().isOpenForLiquidation(account), "Account not open for liquidation"); // require liquidator has enough sUSD require(IERC20(address(synths[sUSD])).balanceOf(liquidator) >= susdAmount, "Not enough sUSD"); uint liquidationPenalty = liquidations().liquidationPenalty(); // What is their debt in sUSD? (uint debtBalance, uint totalDebtIssued, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(account, sUSD); (uint snxRate, bool snxRateInvalid) = exchangeRates().rateAndInvalid(SNX); _requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid); uint collateralForAccount = _collateral(account); uint amountToFixRatio = liquidations().calculateAmountToFixCollateral(debtBalance, _snxToUSD(collateralForAccount, snxRate)); // Cap amount to liquidate to repair collateral ratio based on issuance ratio amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount; // what's the equivalent amount of snx for the amountToLiquidate? uint snxRedeemed = _usdToSnx(amountToLiquidate, snxRate); // Add penalty totalRedeemed = snxRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty)); // if total SNX to redeem is greater than account's collateral // account is under collateralised, liquidate all collateral and reduce sUSD to burn if (totalRedeemed > collateralForAccount) { // set totalRedeemed to all transferable collateral totalRedeemed = collateralForAccount; // whats the equivalent sUSD to burn for all collateral less penalty amountToLiquidate = _snxToUSD( collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)), snxRate ); } // burn sUSD from messageSender (liquidator) and reduce account's debt _burnSynths(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued); // Remove liquidation flag if amount liquidated fixes ratio if (amountToLiquidate == amountToFixRatio) { // Remove liquidation liquidations().removeAccountInLiquidation(account); } } /* ========== INTERNAL FUNCTIONS ========== */ function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure { require(!anyRateIsInvalid, "A synth or SNX rate is invalid"); } function _requireCanIssueOnBehalf(address issueForAddress, address from) internal view { require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf"); } function _requireCanBurnOnBehalf(address burnForAddress, address from) internal view { require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf"); } function _issueSynths( address from, uint amount, bool issueMax ) internal { (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsInvalid) = _remainingIssuableSynths(from); _requireRatesNotInvalid(anyRateIsInvalid); if (!issueMax) { require(amount <= maxIssuable, "Amount too large"); } else { amount = maxIssuable; } // Keep track of the debt they're about to create _addToDebtRegister(from, amount, existingDebt, totalSystemDebt); // record issue timestamp _setLastIssueEvent(from); // Create their synths synths[sUSD].issue(from, amount); // Account for the issued debt in the cache debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit()); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(from); } function _burnSynths( address debtAccount, address burnAccount, uint amount, uint existingDebt, uint totalDebtIssued ) internal returns (uint amountBurnt) { // liquidation requires sUSD to be already settled / not in waiting period // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. amountBurnt = existingDebt < amount ? existingDebt : amount; // Remove liquidated debt from the ledger _removeFromDebtRegister(debtAccount, amountBurnt, existingDebt, totalDebtIssued); // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[sUSD].burn(burnAccount, amountBurnt); // Account for the burnt debt in the cache. debtCache().updateCachedSynthDebtWithRate(sUSD, SafeDecimalMath.unit()); // Store their debtRatio against a fee period to determine their fee/rewards % for the period _appendAccountIssuanceRecord(debtAccount); } // If burning to target, `amount` is ignored, and the correct quantity of sUSD is burnt to reach the target // c-ratio, allowing fees to be claimed. In this case, pending settlements will be skipped as the user // will still have debt remaining after reaching their target. function _voluntaryBurnSynths( address from, uint amount, bool burnToTarget ) internal { if (!burnToTarget) { // If not burning to target, then burning requires that the minimum stake time has elapsed. require(_canBurnSynths(from), "Minimum stake time not reached"); // First settle anything pending into sUSD as burning or issuing impacts the size of the debt pool (, uint refunded, uint numEntriesSettled) = exchanger().settle(from, sUSD); if (numEntriesSettled > 0) { amount = exchanger().calculateAmountAfterSettlement(from, sUSD, amount, refunded); } } (uint existingDebt, uint totalSystemValue, bool anyRateIsInvalid) = _debtBalanceOfAndTotalDebt(from, sUSD); (uint maxIssuableSynthsForAccount, bool snxRateInvalid) = _maxIssuableSynths(from); _requireRatesNotInvalid(anyRateIsInvalid || snxRateInvalid); require(existingDebt > 0, "No debt to forgive"); if (burnToTarget) { amount = existingDebt.sub(maxIssuableSynthsForAccount); } uint amountBurnt = _burnSynths(from, from, amount, existingDebt, totalSystemValue); // Check and remove liquidation if existingDebt after burning is <= maxIssuableSynths // Issuance ratio is fixed so should remove any liquidations if (existingDebt.sub(amountBurnt) <= maxIssuableSynthsForAccount) { liquidations().removeAccountInLiquidation(from); } } function _setLastIssueEvent(address account) internal { // Set the timestamp of the last issueSynths flexibleStorage().setUIntValue( CONTRACT_NAME, keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)), block.timestamp ); } function _appendAccountIssuanceRecord(address from) internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState().issuanceData(from); feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex); } function _addToDebtRegister( address from, uint amount, uint existingDebt, uint totalDebtIssued ) internal { ISynthetixState state = synthetixState(); // What will the new total be including the new value? uint newTotalDebtIssued = amount.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } else { // If they have no debt, they're a new issuer; record this. state.incrementTotalIssuerCount(); } // Save the debt entry parameters state.setCurrentIssuanceData(from, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (state.debtLedgerLength() > 0) { state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } else { state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function _removeFromDebtRegister( address from, uint debtToRemove, uint existingDebt, uint totalDebtIssued ) internal { ISynthetixState state = synthetixState(); // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { state.setCurrentIssuanceData(from, 0); state.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers state.setCurrentIssuanceData(from, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } /* ========== MODIFIERS ========== */ function _onlySynthetix() internal view { require(msg.sender == address(synthetix()), "Issuer: Only the synthetix contract can perform this action"); } modifier onlySynthetix() { _onlySynthetix(); // Use an internal function to save code size. _; } /* ========== EVENTS ========== */ event SynthAdded(bytes32 currencyKey, address synth); event SynthRemoved(bytes32 currencyKey, address synth); }
Remove its contribution from the debt pool snapshot, and invalidate the cache to force a new snapshot.
function removeSynth(bytes32 currencyKey) external onlyOwner { IIssuerInternalDebtCache cache = debtCache(); cache.updateCachedSynthDebtWithRate(currencyKey, 0); cache.updateDebtCacheValidity(true); _removeSynth(currencyKey); }
540,887
[ 1, 3288, 2097, 24880, 628, 326, 18202, 88, 2845, 4439, 16, 471, 11587, 326, 1247, 358, 2944, 279, 394, 4439, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 10503, 451, 12, 3890, 1578, 5462, 653, 13, 3903, 1338, 5541, 288, 203, 3639, 467, 16667, 3061, 758, 23602, 1649, 1247, 273, 18202, 88, 1649, 5621, 203, 3639, 1247, 18, 2725, 9839, 10503, 451, 758, 23602, 1190, 4727, 12, 7095, 653, 16, 374, 1769, 203, 3639, 1247, 18, 2725, 758, 23602, 1649, 19678, 12, 3767, 1769, 203, 203, 3639, 389, 4479, 10503, 451, 12, 7095, 653, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x34aA57231883AFCcE6F31c057a077E5ABe82b108/sources/ReferralCrowdsale.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) { return msg.data; } uint256[50] private __gap; }
2,614,093
[ 1, 17727, 1779, 2973, 326, 783, 4588, 819, 16, 6508, 326, 5793, 434, 326, 2492, 471, 2097, 501, 18, 21572, 4259, 854, 19190, 2319, 3970, 1234, 18, 15330, 471, 1234, 18, 892, 16, 2898, 1410, 486, 506, 15539, 316, 4123, 279, 2657, 21296, 16, 3241, 1347, 21964, 598, 611, 13653, 2191, 17, 20376, 326, 2236, 5431, 471, 8843, 310, 364, 4588, 2026, 486, 506, 326, 3214, 5793, 261, 345, 10247, 487, 392, 2521, 353, 356, 2750, 11748, 2934, 1220, 6835, 353, 1338, 1931, 364, 12110, 16, 5313, 17, 5625, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1772, 10784, 429, 353, 10188, 6934, 288, 203, 97, 203, 203, 203, 565, 445, 1001, 1042, 67, 2738, 1435, 2713, 12562, 288, 203, 3639, 1001, 1042, 67, 2738, 67, 4384, 8707, 5621, 203, 565, 289, 203, 203, 565, 445, 1001, 1042, 67, 2738, 67, 4384, 8707, 1435, 2713, 12562, 288, 203, 565, 289, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 565, 2254, 5034, 63, 3361, 65, 3238, 1001, 14048, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD7134e2265B78DFCF4e9FA4DC65b18F4D5C03220/sources/contracts/bridgeERC20/layerZero/LayerZeroBridgeERC20.sol
Will overflow if the amount is too big
balanceOf[from] = balanceOf[from] - amount;
3,182,954
[ 1, 13670, 9391, 309, 326, 3844, 353, 4885, 5446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 11013, 951, 63, 2080, 65, 273, 11013, 951, 63, 2080, 65, 300, 3844, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xBAda55fA5FF3850fC979455F27F0cA3f1178Be55/sources/contracts/staking/InfinityStaker.sol
@dev Admin function to update rageQuit penalties
function updatePenalties( uint32 _threeMonthPenalty, uint32 _sixMonthPenalty, uint32 _twelveMonthPenalty ) external onlyOwner { require(_threeMonthPenalty > 0 && _threeMonthPenalty < threeMonthPenalty, 'invalid value'); require(_sixMonthPenalty > 0 && _sixMonthPenalty < sixMonthPenalty, 'invalid value'); require(_twelveMonthPenalty > 0 && _twelveMonthPenalty < twelveMonthPenalty, 'invalid value'); threeMonthPenalty = _threeMonthPenalty; sixMonthPenalty = _sixMonthPenalty; twelveMonthPenalty = _twelveMonthPenalty; emit RageQuitPenaltiesUpdated(threeMonthPenalty, sixMonthPenalty, twelveMonthPenalty); }
8,435,770
[ 1, 4446, 445, 358, 1089, 436, 410, 25365, 14264, 2390, 606, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 24251, 2390, 606, 12, 203, 565, 2254, 1578, 389, 451, 992, 5445, 24251, 15006, 16, 203, 565, 2254, 1578, 389, 87, 697, 5445, 24251, 15006, 16, 203, 565, 2254, 1578, 389, 11246, 292, 537, 5445, 24251, 15006, 203, 225, 262, 3903, 1338, 5541, 288, 203, 565, 2583, 24899, 451, 992, 5445, 24251, 15006, 405, 374, 597, 389, 451, 992, 5445, 24251, 15006, 411, 8925, 5445, 24251, 15006, 16, 296, 5387, 460, 8284, 203, 565, 2583, 24899, 87, 697, 5445, 24251, 15006, 405, 374, 597, 389, 87, 697, 5445, 24251, 15006, 411, 5050, 5445, 24251, 15006, 16, 296, 5387, 460, 8284, 203, 565, 2583, 24899, 11246, 292, 537, 5445, 24251, 15006, 405, 374, 597, 389, 11246, 292, 537, 5445, 24251, 15006, 411, 2339, 292, 537, 5445, 24251, 15006, 16, 296, 5387, 460, 8284, 203, 565, 8925, 5445, 24251, 15006, 273, 389, 451, 992, 5445, 24251, 15006, 31, 203, 565, 5050, 5445, 24251, 15006, 273, 389, 87, 697, 5445, 24251, 15006, 31, 203, 565, 2339, 292, 537, 5445, 24251, 15006, 273, 389, 11246, 292, 537, 5445, 24251, 15006, 31, 203, 565, 3626, 534, 410, 25365, 24251, 2390, 606, 7381, 12, 451, 992, 5445, 24251, 15006, 16, 5050, 5445, 24251, 15006, 16, 2339, 292, 537, 5445, 24251, 15006, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "@c-layer/common/contracts/operable/Operable.sol"; import "@c-layer/common/contracts/lifecycle/Pausable.sol"; import "../interface/ITokensale.sol"; /** * @title BaseTokensale * @dev Base Tokensale contract * * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messages * TOS01: token price must be strictly positive * TOS02: price unit must be strictly positive * TOS03: Token transfer must be successfull * TOS04: No ETH to refund * TOS05: Cannot invest 0 tokens * TOS06: Cannot invest if there are no tokens to buy * TOS07: Only exact amount is authorized */ contract BaseTokensale is ITokensale, Operable, Pausable { /* General sale details */ IERC20 internal token_; address payable internal vaultETH_; address internal vaultERC20_; uint256 internal tokenPrice_; uint256 internal priceUnit_; uint256 internal totalRaised_; uint256 internal totalTokensSold_; uint256 internal totalUnspentETH_; uint256 internal totalRefundedETH_; struct Investor { uint256 unspentETH; uint256 invested; uint256 tokens; } mapping(address => Investor) internal investors; /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit ) { require(_tokenPrice > 0, "TOS01"); require(_priceUnit > 0, "TOS02"); token_ = _token; vaultERC20_ = _vaultERC20; vaultETH_ = _vaultETH; tokenPrice_ = _tokenPrice; priceUnit_ = _priceUnit; } /** * @dev fallback function */ //solhint-disable-next-line no-complex-fallback receive() external override payable { investETH(); } /* Investment */ function investETH() public virtual override payable { Investor storage investor = investorInternal(msg.sender); uint256 amountETH = investor.unspentETH + msg.value; investInternal(msg.sender, amountETH, false); } /** * @dev returns the token sold */ function token() public override view returns (IERC20) { return token_; } /** * @dev returns the vault use to */ function vaultETH() public override view returns (address) { return vaultETH_; } /** * @dev returns the vault to receive ETH */ function vaultERC20() public override view returns (address) { return vaultERC20_; } /** * @dev returns token price */ function tokenPrice() public override view returns (uint256) { return tokenPrice_; } /** * @dev returns price unit */ function priceUnit() public override view returns (uint256) { return priceUnit_; } /** * @dev returns total raised */ function totalRaised() public override view returns (uint256) { return totalRaised_; } /** * @dev returns total tokens sold */ function totalTokensSold() public override view returns (uint256) { return totalTokensSold_; } /** * @dev returns total unspent ETH */ function totalUnspentETH() public override view returns (uint256) { return totalUnspentETH_; } /** * @dev returns total refunded ETH */ function totalRefundedETH() public override view returns (uint256) { return totalRefundedETH_; } /** * @dev returns the available supply */ function availableSupply() public override view returns (uint256) { uint256 vaultSupply = token_.balanceOf(vaultERC20_); uint256 allowance = token_.allowance(vaultERC20_, address(this)); return (vaultSupply < allowance) ? vaultSupply : allowance; } /* Investor specific attributes */ function investorUnspentETH(address _investor) public override view returns (uint256) { return investorInternal(_investor).unspentETH; } function investorInvested(address _investor) public override view returns (uint256) { return investorInternal(_investor).invested; } function investorTokens(address _investor) public override view returns (uint256) { return investorInternal(_investor).tokens; } /** * @dev tokenInvestment */ function tokenInvestment(address, uint256 _amount) public virtual override view returns (uint256) { uint256 availableSupplyValue = availableSupply(); uint256 contribution = _amount * priceUnit_ / tokenPrice_; return (contribution < availableSupplyValue) ? contribution : availableSupplyValue; } /** * @dev refund unspentETH ETH many */ function refundManyUnspentETH(address payable[] memory _receivers) public override onlyOperator returns (bool) { for (uint256 i = 0; i < _receivers.length; i++) { refundUnspentETHInternal(_receivers[i]); } return true; } /** * @dev refund unspentETH */ function refundUnspentETH() public override returns (bool) { refundUnspentETHInternal(payable(msg.sender)); return true; } /** * @dev withdraw all ETH funds */ function withdrawAllETHFunds() public override onlyOperator returns (bool) { uint256 balance = address(this).balance; withdrawETHInternal(balance); return true; } /** * @dev fund ETH */ function fundETH() public override payable onlyOperator { emit FundETH(msg.value); } /** * @dev investor internal */ function investorInternal(address _investor) internal virtual view returns (Investor storage) { return investors[_investor]; } /** * @dev eval unspent ETH internal */ function evalUnspentETHInternal( Investor storage _investor, uint256 _investedETH ) internal virtual view returns (uint256) { return _investor.unspentETH + msg.value - _investedETH; } /** * @dev eval investment internal */ function evalInvestmentInternal(uint256 _tokens) internal virtual view returns (uint256, uint256) { uint256 invested = _tokens * tokenPrice_ / priceUnit_; return (invested, _tokens); } /** * @dev distribute tokens internal */ function distributeTokensInternal(address _investor, uint256 _tokens) internal virtual { require( token_.transferFrom(vaultERC20_, _investor, _tokens), "TOS03"); } /** * @dev refund unspentETH internal */ function refundUnspentETHInternal(address payable _investor) internal virtual { Investor storage investor = investorInternal(_investor); require(investor.unspentETH > 0, "TOS04"); uint256 unspentETH = investor.unspentETH; totalRefundedETH_ = totalRefundedETH_ + unspentETH; totalUnspentETH_ = totalUnspentETH_ - unspentETH; investor.unspentETH = 0; // Multiple sends are required for refundManyUnspentETH // solhint-disable-next-line multiple-sends _investor.transfer(unspentETH); emit RefundETH(_investor, unspentETH); } /** * @dev withdraw ETH internal */ function withdrawETHInternal(uint256 _amount) internal virtual { // Send is used after the ERC20 transfer // solhint-disable-next-line multiple-sends vaultETH_.transfer(_amount); emit WithdrawETH(_amount); } /** * @dev invest internal */ function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly) internal virtual whenNotPaused { require(_amount != 0, "TOS05"); Investor storage investor = investorInternal(_investor); uint256 investment = tokenInvestment(_investor, _amount); require(investment != 0, "TOS06"); (uint256 invested, uint256 tokens) = evalInvestmentInternal(investment); if (_exactAmountOnly) { require(invested == _amount, "TOS07"); } else { uint256 unspentETH = evalUnspentETHInternal(investor, invested); totalUnspentETH_ = totalUnspentETH_ - investor.unspentETH + unspentETH; investor.unspentETH = unspentETH; } investor.invested = investor.invested + invested; investor.tokens = investor.tokens + tokens; totalRaised_ = totalRaised_ + invested; totalTokensSold_ = totalTokensSold_ + tokens; emit Investment(_investor, invested, tokens); /* Reentrancy risks: No state change must come below */ distributeTokensInternal(_investor, tokens); uint256 balance = address(this).balance; uint256 withdrawableETH = balance - totalUnspentETH_; if (withdrawableETH != 0) { withdrawETHInternal(withdrawableETH); } } }
* @dev returns the available supply/
function availableSupply() public override view returns (uint256) { uint256 vaultSupply = token_.balanceOf(vaultERC20_); uint256 allowance = token_.allowance(vaultERC20_, address(this)); return (vaultSupply < allowance) ? vaultSupply : allowance; }
2,531,947
[ 1, 6154, 326, 2319, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2319, 3088, 1283, 1435, 1071, 3849, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 9229, 3088, 1283, 273, 1147, 27799, 12296, 951, 12, 26983, 654, 39, 3462, 67, 1769, 203, 565, 2254, 5034, 1699, 1359, 273, 1147, 27799, 5965, 1359, 12, 26983, 654, 39, 3462, 67, 16, 1758, 12, 2211, 10019, 203, 565, 327, 261, 26983, 3088, 1283, 411, 1699, 1359, 13, 692, 9229, 3088, 1283, 294, 1699, 1359, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.20; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); } // ---------------------------------------------------------------------------- // VIOLET ERC20 Standard Token // ---------------------------------------------------------------------------- contract VLTToken is ERC20Interface { using SafeMath for uint256; address public owner = msg.sender; bytes32 public symbol; bytes32 public name; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint256) internal balances; mapping(address => mapping (address => uint256)) internal allowed; modifier onlyOwner() { require(msg.sender == owner); _; } // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function VLTToken() public { symbol = "VAI"; name = "VIOLET"; decimals = 18; _totalSupply = 250000000 * 10**uint256(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _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 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]; } /** * @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) { // allow sending 0 tokens if (_value == 0) { Transfer(msg.sender, _to, _value); // Follow the spec to louch the event when transfer 0 return; } 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 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 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) { // allow sending 0 tokens if (_value == 0) { Transfer(_from, _to, _value); // Follow the spec to louch the event when transfer 0 return; } 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 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; } /** * @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); Transfer(burner, address(0), _value); } /** * 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) { require(_value <= balances[_from]); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowed allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply Burn(_from, _value); Transfer(_from, address(0), _value); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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 Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ViolaCrowdsale * @dev ViolaCrowdsale reserves token from supply when eth is received * funds will be forwarded after the end of crowdsale. Tokens will be claimable * within 7 days after crowdsale ends. */ contract ViolaCrowdsale is Ownable { using SafeMath for uint256; enum State { Deployed, PendingStart, Active, Paused, Ended, Completed } //Status of contract State public status = State.Deployed; // The token being sold VLTToken public violaToken; //For keeping track of whitelist address. cap >0 = whitelisted mapping(address=>uint) public maxBuyCap; //For checking if address passed KYC mapping(address => bool)public addressKYC; //Total wei sum an address has invested mapping(address=>uint) public investedSum; //Total violaToken an address is allocated mapping(address=>uint) public tokensAllocated; //Total violaToken an address purchased externally is allocated mapping(address=>uint) public externalTokensAllocated; //Total bonus violaToken an address is entitled after vesting mapping(address=>uint) public bonusTokensAllocated; //Total bonus violaToken an address purchased externally is entitled after vesting mapping(address=>uint) public externalBonusTokensAllocated; //Store addresses that has registered for crowdsale before (pushed via setWhitelist) //Does not mean whitelisted as it can be revoked. Just to track address for loop address[] public registeredAddress; //Total amount not approved for withdrawal uint256 public totalApprovedAmount = 0; //Start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; uint256 public bonusVestingPeriod = 60 days; /** * Note all values are calculated in wei(uint256) including token amount * 1 ether = 1000000000000000000 wei * 1 viola = 1000000000000000000 vi lawei */ //Address where funds are collected address public wallet; //Min amount investor can purchase uint256 public minWeiToPurchase; // how many token units *in wei* a buyer gets *per wei* uint256 public rate; //Extra bonus token to give *in percentage* uint public bonusTokenRateLevelOne = 20; uint public bonusTokenRateLevelTwo = 15; uint public bonusTokenRateLevelThree = 10; uint public bonusTokenRateLevelFour = 0; //Total amount of tokens allocated for crowdsale uint256 public totalTokensAllocated; //Total amount of tokens reserved from external sources //Sub set of totalTokensAllocated ( totalTokensAllocated - totalReservedTokenAllocated = total tokens allocated for purchases using ether ) uint256 public totalReservedTokenAllocated; //Numbers of token left above 0 to still be considered sold uint256 public leftoverTokensBuffer; /** * event for front end logging */ event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount, uint256 bonusAmount); event ExternalTokenPurchase(address indexed purchaser, uint256 amount, uint256 bonusAmount); event ExternalPurchaseRefunded(address indexed purchaser, uint256 amount, uint256 bonusAmount); event TokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event BonusTokenDistributed(address indexed tokenReceiver, uint256 tokenAmount); event TopupTokenAllocated(address indexed tokenReceiver, uint256 amount, uint256 bonusAmount); event CrowdsalePending(); event CrowdsaleStarted(); event CrowdsaleEnded(); event BonusRateChanged(); event Refunded(address indexed beneficiary, uint256 weiAmount); //Set inital arguments of the crowdsale function initialiseCrowdsale (uint256 _startTime, uint256 _rate, address _tokenAddress, address _wallet) onlyOwner external { require(status == State.Deployed); require(_startTime >= now); require(_rate > 0); require(address(_tokenAddress) != address(0)); require(_wallet != address(0)); startTime = _startTime; endTime = _startTime + 30 days; rate = _rate; wallet = _wallet; violaToken = VLTToken(_tokenAddress); status = State.PendingStart; CrowdsalePending(); } /** * Crowdsale state functions * To track state of current crowdsale */ // To be called by Ethereum alarm clock or anyone //Can only be called successfully when time is valid function startCrowdsale() external { require(withinPeriod()); require(violaToken != address(0)); require(getTokensLeft() > 0); require(status == State.PendingStart); status = State.Active; CrowdsaleStarted(); } //To be called by owner or contract //Ends the crowdsale when tokens are sold out function endCrowdsale() public { if (!tokensHasSoldOut()) { require(msg.sender == owner); } require(status == State.Active); bonusVestingPeriod = now + 60 days; status = State.Ended; CrowdsaleEnded(); } //Emergency pause function pauseCrowdsale() onlyOwner external { require(status == State.Active); status = State.Paused; } //Resume paused crowdsale function unpauseCrowdsale() onlyOwner external { require(status == State.Paused); status = State.Active; } function completeCrowdsale() onlyOwner external { require(hasEnded()); require(violaToken.allowance(owner, this) == 0); status = State.Completed; _forwardFunds(); assert(this.balance == 0); } function burnExtraTokens() onlyOwner external { require(hasEnded()); uint256 extraTokensToBurn = violaToken.allowance(owner, this); violaToken.burnFrom(owner, extraTokensToBurn); assert(violaToken.allowance(owner, this) == 0); } // send ether to the fund collection wallet function _forwardFunds() internal { wallet.transfer(this.balance); } function partialForwardFunds(uint _amountToTransfer) onlyOwner external { require(status == State.Ended); require(_amountToTransfer < totalApprovedAmount); totalApprovedAmount = totalApprovedAmount.sub(_amountToTransfer); wallet.transfer(_amountToTransfer); } /** * Setter functions for crowdsale parameters * Only owner can set values */ function setLeftoverTokensBuffer(uint256 _tokenBuffer) onlyOwner external { require(_tokenBuffer > 0); require(getTokensLeft() >= _tokenBuffer); leftoverTokensBuffer = _tokenBuffer; } //Set the ether to token rate function setRate(uint _rate) onlyOwner external { require(_rate > 0); rate = _rate; } function setBonusTokenRateLevelOne(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelOne = _rate; BonusRateChanged(); } function setBonusTokenRateLevelTwo(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelTwo = _rate; BonusRateChanged(); } function setBonusTokenRateLevelThree(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelThree = _rate; BonusRateChanged(); } function setBonusTokenRateLevelFour(uint _rate) onlyOwner external { //require(_rate > 0); bonusTokenRateLevelFour = _rate; BonusRateChanged(); } function setMinWeiToPurchase(uint _minWeiToPurchase) onlyOwner external { minWeiToPurchase = _minWeiToPurchase; } /** * Whitelisting and KYC functions * Whitelisted address can buy tokens, KYC successful purchaser can claim token. Refund if fail KYC */ //Set the amount of wei an address can purchase up to //@dev Value of 0 = not whitelisted //@dev cap is in *18 decimals* ( 1 token = 1*10^18) function setWhitelistAddress( address _investor, uint _cap ) onlyOwner external { require(_cap > 0); require(_investor != address(0)); maxBuyCap[_investor] = _cap; registeredAddress.push(_investor); //add event } //Remove the address from whitelist function removeWhitelistAddress(address _investor) onlyOwner external { require(_investor != address(0)); maxBuyCap[_investor] = 0; uint256 weiAmount = investedSum[_investor]; if (weiAmount > 0) { _refund(_investor); } } //Flag address as KYC approved. Address is now approved to claim tokens function approveKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = true; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.add(weiAmount); } //Set KYC status as failed. Refund any eth back to address function revokeKYC(address _kycAddress) onlyOwner external { require(_kycAddress != address(0)); addressKYC[_kycAddress] = false; uint256 weiAmount = investedSum[_kycAddress]; totalApprovedAmount = totalApprovedAmount.sub(weiAmount); if (weiAmount > 0) { _refund(_kycAddress); } } /** * Getter functions for crowdsale parameters * Does not use gas */ //Checks if token has been sold out function tokensHasSoldOut() view internal returns (bool) { if (getTokensLeft() <= leftoverTokensBuffer) { return true; } else { return false; } } // @return true if the transaction can buy tokens function withinPeriod() public view returns (bool) { return now >= startTime && now <= endTime; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (status == State.Ended) { return true; } return now > endTime; } function getTokensLeft() public view returns (uint) { return violaToken.allowance(owner, this).sub(totalTokensAllocated); } function transferTokens (address receiver, uint tokenAmount) internal { require(violaToken.transferFrom(owner, receiver, tokenAmount)); } function getTimeBasedBonusRate() public view returns(uint) { bool bonusDuration1 = now >= startTime && now <= (startTime + 1 days); //First 24hr bool bonusDuration2 = now > (startTime + 1 days) && now <= (startTime + 3 days);//Next 48 hr bool bonusDuration3 = now > (startTime + 3 days) && now <= (startTime + 10 days);//4th to 10th day bool bonusDuration4 = now > (startTime + 10 days) && now <= endTime;//11th day onwards if (bonusDuration1) { return bonusTokenRateLevelOne; } else if (bonusDuration2) { return bonusTokenRateLevelTwo; } else if (bonusDuration3) { return bonusTokenRateLevelThree; } else if (bonusDuration4) { return bonusTokenRateLevelFour; } else { return 0; } } function getTotalTokensByAddress(address _investor) public view returns(uint) { return getTotalNormalTokensByAddress(_investor).add(getTotalBonusTokensByAddress(_investor)); } function getTotalNormalTokensByAddress(address _investor) public view returns(uint) { return tokensAllocated[_investor].add(externalTokensAllocated[_investor]); } function getTotalBonusTokensByAddress(address _investor) public view returns(uint) { return bonusTokensAllocated[_investor].add(externalBonusTokensAllocated[_investor]); } function _clearTotalNormalTokensByAddress(address _investor) internal { tokensAllocated[_investor] = 0; externalTokensAllocated[_investor] = 0; } function _clearTotalBonusTokensByAddress(address _investor) internal { bonusTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; } /** * Functions to handle buy tokens * Fallback function as entry point for eth */ // Called when ether is sent to contract function () external payable { buyTokens(msg.sender); } //Used to buy tokens function buyTokens(address investor) internal { require(status == State.Active); require(msg.value >= minWeiToPurchase); uint weiAmount = msg.value; checkCapAndRecord(investor,weiAmount); allocateToken(investor,weiAmount); } //Internal call to check max user cap function checkCapAndRecord(address investor, uint weiAmount) internal { uint remaindingCap = maxBuyCap[investor]; require(remaindingCap >= weiAmount); maxBuyCap[investor] = remaindingCap.sub(weiAmount); investedSum[investor] = investedSum[investor].add(weiAmount); } //Internal call to allocated tokens purchased function allocateToken(address investor, uint weiAmount) internal { // calculate token amount to be created uint tokens = weiAmount.mul(rate); uint bonusTokens = tokens.mul(getTimeBasedBonusRate()).div(100); uint tokensToAllocate = tokens.add(bonusTokens); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(tokensToAllocate); tokensAllocated[investor] = tokensAllocated[investor].add(tokens); bonusTokensAllocated[investor] = bonusTokensAllocated[investor].add(bonusTokens); if (tokensHasSoldOut()) { endCrowdsale(); } TokenPurchase(investor, weiAmount, tokens, bonusTokens); } /** * Functions for refunds & claim tokens * */ //Refund users in case of unsuccessful crowdsale function _refund(address _investor) internal { uint256 investedAmt = investedSum[_investor]; require(investedAmt > 0); uint totalInvestorTokens = tokensAllocated[_investor].add(bonusTokensAllocated[_investor]); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); } _clearAddressFromCrowdsale(_investor); _investor.transfer(investedAmt); Refunded(_investor, investedAmt); } //Partial refund users function refundPartial(address _investor, uint _refundAmt, uint _tokenAmt, uint _bonusTokenAmt) onlyOwner external { uint investedAmt = investedSum[_investor]; require(investedAmt > _refundAmt); require(tokensAllocated[_investor] > _tokenAmt); require(bonusTokensAllocated[_investor] > _bonusTokenAmt); investedSum[_investor] = investedSum[_investor].sub(_refundAmt); tokensAllocated[_investor] = tokensAllocated[_investor].sub(_tokenAmt); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].sub(_bonusTokenAmt); uint totalRefundTokens = _tokenAmt.add(_bonusTokenAmt); if (status == State.Active) { //Refunded tokens go back to sale pool totalTokensAllocated = totalTokensAllocated.sub(totalRefundTokens); } _investor.transfer(_refundAmt); Refunded(_investor, _refundAmt); } //Used by investor to claim token function claimTokens() external { require(hasEnded()); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver, tokensToClaim); } //Used by investor to claim bonus token function claimBonusTokens() external { require(hasEnded()); require(now >= bonusVestingPeriod); require(addressKYC[msg.sender]); address tokenReceiver = msg.sender; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); violaToken.transferFrom(owner, tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver, tokensToClaim); } //Used by owner to distribute bonus token function distributeBonusTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); require(now >= bonusVestingPeriod); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalBonusTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalBonusTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); BonusTokenDistributed(tokenReceiver,tokensToClaim); } //Used by owner to distribute token function distributeICOTokens(address _tokenReceiver) onlyOwner external { require(hasEnded()); address tokenReceiver = _tokenReceiver; uint tokensToClaim = getTotalNormalTokensByAddress(tokenReceiver); require(tokensToClaim > 0); _clearTotalNormalTokensByAddress(tokenReceiver); transferTokens(tokenReceiver, tokensToClaim); TokenDistributed(tokenReceiver,tokensToClaim); } //For owner to reserve token for presale // function reserveTokens(uint _amount) onlyOwner external { // require(getTokensLeft() >= _amount); // totalTokensAllocated = totalTokensAllocated.add(_amount); // totalReservedTokenAllocated = totalReservedTokenAllocated.add(_amount); // } // //To distribute tokens not allocated by crowdsale contract // function distributePresaleTokens(address _tokenReceiver, uint _amount) onlyOwner external { // require(hasEnded()); // require(_tokenReceiver != address(0)); // require(_amount > 0); // violaToken.transferFrom(owner, _tokenReceiver, _amount); // TokenDistributed(_tokenReceiver,_amount); // } //For external purchases & pre-sale via btc/fiat function externalPurchaseTokens(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(_amount > 0); uint256 totalTokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= totalTokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(totalTokensToAllocate); totalReservedTokenAllocated = totalReservedTokenAllocated.add(totalTokensToAllocate); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].add(_amount); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].add(_bonusAmount); ExternalTokenPurchase(_investor, _amount, _bonusAmount); } function refundAllExternalPurchase(address _investor) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] > 0); uint externalTokens = externalTokensAllocated[_investor]; uint externalBonusTokens = externalBonusTokensAllocated[_investor]; externalTokensAllocated[_investor] = 0; externalBonusTokensAllocated[_investor] = 0; uint totalInvestorTokens = externalTokens.add(externalBonusTokens); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalInvestorTokens); totalTokensAllocated = totalTokensAllocated.sub(totalInvestorTokens); ExternalPurchaseRefunded(_investor,externalTokens,externalBonusTokens); } function refundExternalPurchase(address _investor, uint _amountToRefund, uint _bonusAmountToRefund) onlyOwner external { require(_investor != address(0)); require(externalTokensAllocated[_investor] >= _amountToRefund); require(externalBonusTokensAllocated[_investor] >= _bonusAmountToRefund); uint totalTokensToRefund = _amountToRefund.add(_bonusAmountToRefund); externalTokensAllocated[_investor] = externalTokensAllocated[_investor].sub(_amountToRefund); externalBonusTokensAllocated[_investor] = externalBonusTokensAllocated[_investor].sub(_bonusAmountToRefund); totalReservedTokenAllocated = totalReservedTokenAllocated.sub(totalTokensToRefund); totalTokensAllocated = totalTokensAllocated.sub(totalTokensToRefund); ExternalPurchaseRefunded(_investor,_amountToRefund,_bonusAmountToRefund); } function _clearAddressFromCrowdsale(address _investor) internal { tokensAllocated[_investor] = 0; bonusTokensAllocated[_investor] = 0; investedSum[_investor] = 0; maxBuyCap[_investor] = 0; } function allocateTopupToken(address _investor, uint _amount, uint _bonusAmount) onlyOwner external { require(hasEnded()); require(_amount > 0); uint256 tokensToAllocate = _amount.add(_bonusAmount); require(getTokensLeft() >= tokensToAllocate); totalTokensAllocated = totalTokensAllocated.add(_amount); tokensAllocated[_investor] = tokensAllocated[_investor].add(_amount); bonusTokensAllocated[_investor] = bonusTokensAllocated[_investor].add(_bonusAmount); TopupTokenAllocated(_investor, _amount, _bonusAmount); } //For cases where token are mistakenly sent / airdrops function emergencyERC20Drain( ERC20 token, uint amount ) external onlyOwner { require(status == State.Completed); token.transfer(owner,amount); } }
Update totalSupply
_totalSupply = _totalSupply.sub(_value);
5,343,190
[ 1, 1891, 2078, 3088, 1283, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 24899, 1132, 1769, 1171, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xC597F86424EEb6599Ea40f999DBB739e3Aca5d82/sources/SLEther.sol
* @title SashimiLending's SLEther Contract @notice SLToken which wraps Ether @author SashimiLending/
contract SLEther is SLToken { constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); admin = admin_; } function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } function liquidateBorrow(address borrower, SLToken slTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, slTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } function doTransferIn(address from, uint amount) internal returns (uint) { require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal { to.transfer(amount); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } }
15,603,737
[ 1, 55, 961, 381, 77, 48, 2846, 1807, 348, 900, 1136, 13456, 225, 348, 48, 1345, 1492, 9059, 512, 1136, 225, 348, 961, 381, 77, 48, 2846, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 900, 1136, 353, 348, 48, 1345, 288, 203, 565, 3885, 12, 799, 337, 1539, 1358, 532, 337, 1539, 67, 16, 203, 7734, 5294, 395, 4727, 1488, 16513, 4727, 1488, 67, 16, 203, 7734, 2254, 2172, 11688, 4727, 49, 970, 21269, 67, 16, 203, 7734, 533, 3778, 508, 67, 16, 203, 7734, 533, 3778, 3273, 67, 16, 203, 7734, 2254, 28, 15105, 67, 16, 203, 203, 7734, 1758, 8843, 429, 3981, 67, 13, 1071, 288, 203, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 203, 3639, 4046, 12, 832, 337, 1539, 67, 16, 16513, 4727, 1488, 67, 16, 2172, 11688, 4727, 49, 970, 21269, 67, 16, 508, 67, 16, 3273, 67, 16, 15105, 67, 1769, 203, 203, 3639, 3981, 273, 3981, 67, 31, 203, 565, 289, 203, 203, 203, 203, 565, 445, 312, 474, 1435, 3903, 8843, 429, 288, 203, 3639, 261, 11890, 393, 16, 13, 273, 312, 474, 3061, 12, 3576, 18, 1132, 1769, 203, 3639, 2583, 2279, 668, 12, 370, 16, 315, 81, 474, 2535, 8863, 203, 565, 289, 203, 203, 565, 445, 283, 24903, 12, 11890, 283, 24903, 5157, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 327, 283, 24903, 3061, 12, 266, 24903, 5157, 1769, 203, 565, 289, 203, 203, 565, 445, 283, 24903, 14655, 6291, 12, 11890, 283, 24903, 6275, 13, 3903, 1135, 261, 11890, 13, 288, 203, 3639, 327, 283, 24903, 14655, 6291, 3061, 12, 266, 24903, 6275, 1769, 203, 565, 289, 203, 203, 565, 445, 29759, 12, 11890, 29759, 6275, 13, 3903, 1135, 261, 11890, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./interfaces/IERC20.sol"; import "./libraries/SafeERC20.sol"; import "./libraries/ERC20.sol"; import "./libraries/EnumerableSet.sol"; import "./libraries/SafeMath.sol"; import "./libraries/Ownable.sol"; import "./xLessToken.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to LessSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // LessSwap must mint EXACTLY the same amount of LessSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of xLess. He can make xLess and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once xLESS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of xLESSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accXLessPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accXLessPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. xLESSs to distribute per block. uint256 lastRewardBlock; // Last block number that xLESSs distribution occurs. uint256 accXLessPerShare; // Accumulated xLESSs per share, times 1e12. See below. } // The xLESS TOKEN! xLessToken public xless; // Dev address. address public devaddr; // Block number when bonus xLESS period ends. uint256 public bonusEndBlock; // xLESS tokens created per block. uint256 public xlessPerBlock; // Bonus muliplier for early xless makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when xLESS mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( xLessToken _xless, address _devaddr, uint256 _xlessPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { xless = _xless; devaddr = _devaddr; xlessPerBlock = _xlessPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accXLessPerShare: 0 }) ); } function updateRewardPerBlock(uint256 _rewardPerBlock) public onlyOwner { xlessPerBlock = _rewardPerBlock; } function updateStartBlock(uint256 _block) public onlyOwner { startBlock = _block; } function updateBonusEndBlock(uint256 _block) public onlyOwner { bonusEndBlock = _block; } // Update the given pool's xLESS allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending xLESSs on frontend. function pendingXLess(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accXLessPerShare = pool.accXLessPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 xlessReward = multiplier .mul(xlessPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accXLessPerShare = accXLessPerShare.add( xlessReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accXLessPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 xlessReward = multiplier .mul(xlessPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); xless.transfer(devaddr, xlessReward.div(10)); pool.accXLessPerShare = pool.accXLessPerShare.add( xlessReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for xLESS allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accXLessPerShare) .div(1e12) .sub(user.rewardDebt); safeXLessTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accXLessPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accXLessPerShare).div(1e12).sub( user.rewardDebt ); safeXLessTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accXLessPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe xless transfer function, just in case if rounding error causes pool to not have enough xLESSs. function safeXLessTransfer(address _to, uint256 _amount) internal { uint256 xlessBal = xless.balanceOf(address(this)); if (_amount > xlessBal) { xless.transfer(_to, xlessBal); } else { xless.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } // SPDX-License-Identifier: GPL-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) { // 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: GPL-3.0 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: GPL-3.0 pragma solidity ^0.6.12; import "./Address.sol"; import "./Context.sol"; import "./SafeMath.sol"; import "../interfaces/IERC20.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) _balances; mapping(address => mapping(address => uint256)) _allowances; uint256 _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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_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 override returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @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: GPL-3.0 pragma solidity ^0.6.12; /** * @title Owned * @dev Basic contract for authorization control. * @author dicether */ contract Ownable { address public owner; address public pendingOwner; event LogOwnerShipTransferred( address indexed previousOwner, address indexed newOwner ); event LogOwnerShipTransferInitiated( address indexed previousOwner, address indexed newOwner ); /** * @dev Modifier, which throws if called by other account than owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Set contract creator as initial owner */ constructor() public { owner = msg.sender; pendingOwner = address(0); } /** * @dev Allows the current owner to set the pendingOwner address. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { pendingOwner = _newOwner; emit LogOwnerShipTransferInitiated(owner, _newOwner); } /** * @dev PendingOwner can accept ownership. */ function claimOwnership() public onlyPendingOwner { owner = pendingOwner; pendingOwner = address(0); emit LogOwnerShipTransferred(owner, pendingOwner); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "./Address.sol"; import "./SafeMath.sol"; import "../interfaces/IERC20.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: GPL-3.0 pragma solidity ^0.6.12; // File: @openzeppelin/contracts/math/SafeMath.sol /** * @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.12; import "./libraries/ERC20.sol"; import "./libraries/Ownable.sol"; // xLessToken with Governance. contract xLessToken is ERC20, Ownable { constructor() public ERC20("xLessToken", "xLESS") { _mint(msg.sender, 56000000 * (10**uint256(decimals()))); // xLess Token Initial Supply 56m } /// @dev notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @dev notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @dev notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @dev notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @dev notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @dev 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)"); /// @dev notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @dev notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @dev notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @dev 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]; } /** * @dev 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); } /** * @dev notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "xLESS::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "xLESS::delegateBySig: invalid nonce" ); require(now <= expiry, "xLESS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev 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; } /** * @dev notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "xLESS::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 xLESSs (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, "xLESS::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @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); }
411,584
[ 1, 986, 279, 460, 358, 279, 444, 18, 531, 12, 21, 2934, 2860, 638, 309, 326, 460, 1703, 3096, 358, 326, 444, 16, 716, 353, 309, 518, 1703, 486, 1818, 3430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 2160, 1578, 694, 2502, 389, 542, 16, 1731, 1578, 389, 1132, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 389, 1289, 24899, 542, 6315, 7872, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // solhint-disable-line /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="274342534267465f4e484a5d4249094448">[email&#160;protected]</a>> (https://github.com/dete) 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 OpinionToken is ERC721 { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new opinion comes into existence. 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); /// @dev Transfer event as defined in current draft of ERC721. /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "Cryptopinions"; // solhint-disable-line string public constant SYMBOL = "OpinionToken"; // solhint-disable-line string public constant DEFAULT_TEXT = ""; uint256 private firstStepLimit = 0.053613 ether; uint256 private secondStepLimit = 0.564957 ether; uint256 private numIssued=5; //number of tokens issued initially uint256 private constant stepMultiplier=2;//multiplier for initial opinion registration cost, not sponsorship uint256 private startingPrice = 0.001 ether; //will increase every token issued by stepMultiplier times uint256 private sponsorStartingCost=0.01 ether;//initial cost to sponsor an opinion //uint256 private currentIssueRemaining; /*** STORAGE ***/ /// @dev A mapping from opinion IDs to the address that owns them. All opinions have /// some valid owner address. mapping (uint256 => address) public opinionIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from opinionIDs to an address that has been approved to call /// transferFrom(). Each opinion can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public opinionIndexToApproved; // @dev A mapping from opinionIDs to the price of the token. mapping (uint256 => uint256) private opinionIndexToPrice; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; /*** DATATYPES ***/ struct Opinion { string text; bool claimed; bool deleted; uint8 comment; address sponsor; address antisponsor; uint256 totalsponsored; uint256 totalantisponsored; uint256 timestamp; } Opinion[] private opinions; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function OpinionToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); opinionIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates initial set of opinions. Can only be called once. function createInitialItems() public onlyCOO { require(opinions.length==0); _createOpinionSet(); } /// @notice Returns all the relevant information about a specific opinion. /// @param _tokenId The tokenId of the opinion of interest. function getOpinion(uint256 _tokenId) public view returns ( uint256 sellingPrice, address owner, address sponsor, address antisponsor, uint256 amountsponsored, uint256 amountantisponsored, uint8 acomment, uint256 timestamp, string opinionText ) { Opinion storage opinion = opinions[_tokenId]; opinionText = opinion.text; sellingPrice = opinionIndexToPrice[_tokenId]; owner = opinionIndexToOwner[_tokenId]; acomment=opinion.comment; sponsor=opinion.sponsor; antisponsor=opinion.antisponsor; amountsponsored=opinion.totalsponsored; amountantisponsored=opinion.totalantisponsored; timestamp=opinion.timestamp; } function compareStrings (string a, string b) public pure returns (bool){ return keccak256(a) == keccak256(b); } function hasDuplicate(string _tocheck) public view returns (bool){ return hasPriorDuplicate(_tocheck,opinions.length); } function hasPriorDuplicate(string _tocheck,uint256 index) public view returns (bool){ for(uint i = 0; i<index; i++){ if(compareStrings(_tocheck,opinions[i].text)){ return true; } } return false; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = opinionIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { //ensure comment corresponds to status of token. Tokens with a comment of 0 are unregistered. require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); // Making sure sent amount is greater than or equal to the sellingPrice uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); } else if (sellingPrice < secondStepLimit) { // second stage opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); } else { // third stage opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ ceoAddress.transfer(sellingPrice); //eth for initial antisponsor goes to Cryptopinions, because you wouldn&#39;t want it to go to the creator of an opinion you don&#39;t like } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } //lets you permanently delete someone elses opinion. function deleteThis(uint256 _tokenId) public payable{ //Cost is 1 eth or five times the current valuation of the opinion, whichever is higher. uint256 sellingPrice = SafeMath.mul(opinionIndexToPrice[_tokenId],5); if(sellingPrice<1 ether){ sellingPrice=1 ether; } require(msg.value >= sellingPrice); ceoAddress.transfer(sellingPrice); Opinion storage opinion = opinions[_tokenId]; opinion.deleted=true; uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); msg.sender.transfer(purchaseExcess); } // Allows someone to send ether and obtain the (unclaimed only) token function registerOpinion(uint256 _tokenId,string _newOpinion) public payable { //Set opinion to the new opinion _initOpinion(_tokenId,_newOpinion); address oldOwner = opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = opinionIndexToPrice[_tokenId]; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 payment = sellingPrice; uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); opinionIndexToPrice[_tokenId] = sponsorStartingCost; //initial cost to sponsor _transfer(oldOwner, newOwner, _tokenId); ceoAddress.transfer(payment); TokenSold(_tokenId, sellingPrice, opinionIndexToPrice[_tokenId], oldOwner, newOwner, opinions[_tokenId].text); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return opinionIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { _setCEO(_newCEO); } function _setCEO(address _newCEO) private{ require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = opinionIndexToOwner[_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); } /// @param _owner The owner whose celebrity tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly /// expensive (it walks the entire opinions array looking for opinions belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalOpinions = totalSupply(); uint256 resultIndex = 0; uint256 opinionId; for (opinionId = 0; opinionId <= totalOpinions; opinionId++) { if (opinionIndexToOwner[opinionId] == _owner) { result[resultIndex] = opinionId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return opinions.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } //Allows purchase of the entire contract. All revenue provisioned to ceoAddress will go to the new address specified. //If you contact us following purchase we will transfer domain, website source code etc. to you free of charge, otherwise we will continue to maintain the frontend site for 1 year. uint256 contractPrice=300 ether; function buyCryptopinions(address _newCEO) payable public{ require(msg.value >= contractPrice); ceoAddress.transfer(msg.value); _setCEO(_newCEO); _setPrice(9999999 ether); } function setPrice(uint256 newprice) public onlyCEO{ _setPrice(newprice); } function _setPrice(uint256 newprice) private{ contractPrice=newprice; } /*** 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 opinionIndexToApproved[_tokenId] == _to; } function _createOpinionSet() private { for(uint i = 0; i<numIssued; i++){ _createOpinion(DEFAULT_TEXT,ceoAddress,startingPrice); } //startingPrice = SafeMath.mul(startingPrice,stepMultiplier); //increase the price for the next set of tokens //currentIssueRemaining=numIssued; } //for registering an Opinion function _initOpinion(uint256 _tokenId,string _newOpinion) private { Opinion storage opinion = opinions[_tokenId]; opinion.timestamp=now; opinion.text=_newOpinion; opinion.comment=1; require(!opinion.claimed); uint256 newprice=SafeMath.mul(stepMultiplier,opinionIndexToPrice[_tokenId]); //max price 1 eth if(newprice > 0.1 ether){ //max price for a new opinion, 1 ether newprice=0.1 ether; } _createOpinion("",ceoAddress,newprice); //make a new opinion for someone else to buy opinion.claimed=true; //currentIssueRemaining=SafeMath.sub(currentIssueRemaining,1); //if this is the last remaining token for sale, issue more //if(currentIssueRemaining == 0){ // _createOpinionSet(); //} } /// For creating Opinion function _createOpinion(string _name, address _owner, uint256 _price) private { Opinion memory _opinion = Opinion({ text: _name, claimed: false, deleted: false, comment: 0, sponsor: _owner, antisponsor: ceoAddress, totalsponsored:0, totalantisponsored:0, timestamp:now }); uint256 newOpinionId = opinions.push(_opinion) - 1; // It&#39;s probably never going to happen, 4 billion tokens are A LOT, but // let&#39;s just be 100% sure we never let this happen. require(newOpinionId == uint256(uint32(newOpinionId))); Birth(newOpinionId, _name, _owner); opinionIndexToPrice[newOpinionId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newOpinionId); } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == opinionIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @dev Assigns ownership of a specific opinion to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of opinions is capped to 2^32 we can&#39;t overflow this ownershipTokenCount[_to]++; //transfer ownership opinionIndexToOwner[_tokenId] = _to; // When creating new opinions _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete opinionIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } } 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; } }
uint256 private currentIssueRemaining; @dev A mapping from owner address to count of tokens that address owns. Used internally inside balanceOf() to resolve ownership count. @dev A mapping from opinionIDs to the price of the token. The addresses of the accounts (or contracts) that can execute actions within each roles.
contract OpinionToken is ERC721 { event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); event Transfer(address from, address to, uint256 tokenId); string public constant DEFAULT_TEXT = ""; uint256 private firstStepLimit = 0.053613 ether; uint256 private secondStepLimit = 0.564957 ether; mapping (uint256 => address) public opinionIndexToOwner; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) public opinionIndexToApproved; mapping (uint256 => uint256) private opinionIndexToPrice; address public ceoAddress; address public cooAddress; struct Opinion { string text; bool claimed; bool deleted; uint8 comment; address sponsor; address antisponsor; uint256 totalsponsored; uint256 totalantisponsored; uint256 timestamp; } Opinion[] private opinions; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } function OpinionToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; } function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); opinionIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function createInitialItems() public onlyCOO { require(opinions.length==0); _createOpinionSet(); } function getOpinion(uint256 _tokenId) public view returns ( uint256 sellingPrice, address owner, address sponsor, address antisponsor, uint256 amountsponsored, uint256 amountantisponsored, uint8 acomment, uint256 timestamp, string opinionText ) { Opinion storage opinion = opinions[_tokenId]; opinionText = opinion.text; sellingPrice = opinionIndexToPrice[_tokenId]; owner = opinionIndexToOwner[_tokenId]; acomment=opinion.comment; sponsor=opinion.sponsor; antisponsor=opinion.antisponsor; amountsponsored=opinion.totalsponsored; amountantisponsored=opinion.totalantisponsored; timestamp=opinion.timestamp; } function compareStrings (string a, string b) public pure returns (bool){ return keccak256(a) == keccak256(b); } function hasDuplicate(string _tocheck) public view returns (bool){ return hasPriorDuplicate(_tocheck,opinions.length); } function hasPriorDuplicate(string _tocheck,uint256 index) public view returns (bool){ for(uint i = 0; i<index; i++){ if(compareStrings(_tocheck,opinions[i].text)){ return true; } } return false; } function hasPriorDuplicate(string _tocheck,uint256 index) public view returns (bool){ for(uint i = 0; i<index; i++){ if(compareStrings(_tocheck,opinions[i].text)){ return true; } } return false; } function hasPriorDuplicate(string _tocheck,uint256 index) public view returns (bool){ for(uint i = 0; i<index; i++){ if(compareStrings(_tocheck,opinions[i].text)){ return true; } } return false; } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = opinionIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } } else if (sellingPrice < secondStepLimit) { } else { function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function sponsorOpinion(uint256 _tokenId,uint8 comment,bool _likesOpinion) public payable { require(comment!=0); require((_likesOpinion && comment<100) || (!_likesOpinion && comment>100)); address sponsorAdr = msg.sender; require(_addressNotNull(sponsorAdr)); uint256 sellingPrice = opinionIndexToPrice[_tokenId]; address currentOwner=opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; require(_addressNotNull(newOwner)); require(_addressNotNull(currentOwner)); require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 ownerTake=uint256(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); if (sellingPrice < firstStepLimit) { opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 90); opinionIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 90); } Opinion storage opinion = opinions[_tokenId]; require(opinion.claimed); require(sponsorAdr!=opinion.sponsor); require(sponsorAdr!=opinion.antisponsor); require(sponsorAdr!=currentOwner); opinion.comment=comment; if(_likesOpinion){ if(_addressNotNull(opinion.sponsor)){ opinion.sponsor.transfer(payment); currentOwner.transfer(ownerTake); } else{ currentOwner.transfer(sellingPrice); } opinion.sponsor=sponsorAdr; opinion.totalsponsored=SafeMath.add(opinion.totalsponsored,sellingPrice); } else{ if(_addressNotNull(opinion.sponsor)){ opinion.antisponsor.transfer(payment); ceoAddress.transfer(ownerTake); } else{ } opinion.antisponsor=sponsorAdr; opinion.totalantisponsored=SafeMath.add(opinion.totalantisponsored,sellingPrice); } msg.sender.transfer(purchaseExcess); } function deleteThis(uint256 _tokenId) public payable{ uint256 sellingPrice = SafeMath.mul(opinionIndexToPrice[_tokenId],5); if(sellingPrice<1 ether){ sellingPrice=1 ether; } require(msg.value >= sellingPrice); ceoAddress.transfer(sellingPrice); Opinion storage opinion = opinions[_tokenId]; opinion.deleted=true; uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); msg.sender.transfer(purchaseExcess); } function deleteThis(uint256 _tokenId) public payable{ uint256 sellingPrice = SafeMath.mul(opinionIndexToPrice[_tokenId],5); if(sellingPrice<1 ether){ sellingPrice=1 ether; } require(msg.value >= sellingPrice); ceoAddress.transfer(sellingPrice); Opinion storage opinion = opinions[_tokenId]; opinion.deleted=true; uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); msg.sender.transfer(purchaseExcess); } function registerOpinion(uint256 _tokenId,string _newOpinion) public payable { _initOpinion(_tokenId,_newOpinion); address oldOwner = opinionIndexToOwner[_tokenId]; address newOwner = msg.sender; uint256 sellingPrice = opinionIndexToPrice[_tokenId]; require(oldOwner != newOwner); require(_addressNotNull(newOwner)); require(msg.value >= sellingPrice); uint256 payment = sellingPrice; uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); _transfer(oldOwner, newOwner, _tokenId); ceoAddress.transfer(payment); TokenSold(_tokenId, sellingPrice, opinionIndexToPrice[_tokenId], oldOwner, newOwner, opinions[_tokenId].text); msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return opinionIndexToPrice[_tokenId]; } function setCEO(address _newCEO) public onlyCEO { _setCEO(_newCEO); } function _setCEO(address _newCEO) private{ require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function symbol() public pure returns (string) { return SYMBOL; } function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = opinionIndexToOwner[_tokenId]; require(_addressNotNull(newOwner)); require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalOpinions = totalSupply(); uint256 resultIndex = 0; uint256 opinionId; for (opinionId = 0; opinionId <= totalOpinions; opinionId++) { if (opinionIndexToOwner[opinionId] == _owner) { result[resultIndex] = opinionId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalOpinions = totalSupply(); uint256 resultIndex = 0; uint256 opinionId; for (opinionId = 0; opinionId <= totalOpinions; opinionId++) { if (opinionIndexToOwner[opinionId] == _owner) { result[resultIndex] = opinionId; resultIndex++; } } return result; } } } else { function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalOpinions = totalSupply(); uint256 resultIndex = 0; uint256 opinionId; for (opinionId = 0; opinionId <= totalOpinions; opinionId++) { if (opinionIndexToOwner[opinionId] == _owner) { result[resultIndex] = opinionId; resultIndex++; } } return result; } } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 totalOpinions = totalSupply(); uint256 resultIndex = 0; uint256 opinionId; for (opinionId = 0; opinionId <= totalOpinions; opinionId++) { if (opinionIndexToOwner[opinionId] == _owner) { result[resultIndex] = opinionId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { return opinions.length; } function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } uint256 contractPrice=300 ether; function buyCryptopinions(address _newCEO) payable public{ require(msg.value >= contractPrice); ceoAddress.transfer(msg.value); _setCEO(_newCEO); _setPrice(9999999 ether); } function setPrice(uint256 newprice) public onlyCEO{ _setPrice(newprice); } function _setPrice(uint256 newprice) private{ contractPrice=newprice; } function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return opinionIndexToApproved[_tokenId] == _to; } function _createOpinionSet() private { for(uint i = 0; i<numIssued; i++){ _createOpinion(DEFAULT_TEXT,ceoAddress,startingPrice); } } function _createOpinionSet() private { for(uint i = 0; i<numIssued; i++){ _createOpinion(DEFAULT_TEXT,ceoAddress,startingPrice); } } function _initOpinion(uint256 _tokenId,string _newOpinion) private { Opinion storage opinion = opinions[_tokenId]; opinion.timestamp=now; opinion.text=_newOpinion; opinion.comment=1; require(!opinion.claimed); uint256 newprice=SafeMath.mul(stepMultiplier,opinionIndexToPrice[_tokenId]); newprice=0.1 ether; } opinion.claimed=true; }
10,540,573
[ 1, 11890, 5034, 3238, 783, 12956, 11429, 31, 225, 432, 2874, 628, 3410, 1758, 358, 1056, 434, 2430, 716, 1758, 29065, 18, 225, 10286, 12963, 4832, 11013, 951, 1435, 358, 2245, 23178, 1056, 18, 225, 432, 2874, 628, 1061, 267, 285, 5103, 358, 326, 6205, 434, 326, 1147, 18, 1021, 6138, 434, 326, 9484, 261, 280, 20092, 13, 716, 848, 1836, 4209, 3470, 1517, 4900, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6066, 267, 285, 1345, 353, 4232, 39, 27, 5340, 288, 203, 203, 203, 225, 871, 605, 10542, 12, 11890, 5034, 1147, 548, 16, 533, 508, 16, 1758, 3410, 1769, 203, 203, 225, 871, 3155, 55, 1673, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 1592, 5147, 16, 2254, 5034, 394, 5147, 16, 1758, 2807, 5541, 16, 1758, 5657, 1224, 16, 533, 508, 1769, 203, 203, 225, 871, 12279, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 1769, 203, 203, 203, 225, 533, 1071, 5381, 3331, 67, 5151, 273, 1408, 31, 203, 203, 225, 2254, 5034, 3238, 1122, 4160, 3039, 273, 225, 374, 18, 6260, 5718, 3437, 225, 2437, 31, 203, 225, 2254, 5034, 3238, 2205, 4160, 3039, 273, 374, 18, 25, 1105, 8778, 27, 225, 2437, 31, 203, 203, 225, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 1061, 267, 285, 1016, 774, 5541, 31, 203, 203, 225, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 23178, 1345, 1380, 31, 203, 203, 225, 2874, 261, 11890, 5034, 516, 1758, 13, 1071, 1061, 267, 285, 1016, 774, 31639, 31, 203, 203, 225, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 3238, 1061, 267, 285, 1016, 774, 5147, 31, 203, 21281, 225, 1758, 1071, 276, 4361, 1887, 31, 203, 225, 1758, 1071, 1825, 83, 1887, 31, 203, 203, 225, 1958, 6066, 267, 285, 288, 203, 565, 533, 977, 31, 203, 565, 1426, 7516, 329, 31, 203, 565, 1426, 4282, 31, 203, 565, 2254, 28, 2879, 31, 203, 565, 1758, 272, 500, 2467, 2 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; // Interface for our erc20 token interface IToken { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom( address from, address to, uint256 tokens ) external returns (bool success); function mint(address to, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } contract CudlFinance is Initializable, ERC721HolderUpgradeable, OwnableUpgradeable { address public mooncats; address public PONDERWARE; address public MUSE_DAO; address public MUSE_DEVS; uint256 public gas; // if gas higher then this you can't kill uint256 public lastGas; //here we record last gas paid, to keep track of chain gas. If gas is high, no pets can die. IToken public token; struct Pet { address nft; uint256 id; } mapping(address => bool) public supportedNfts; mapping(uint256 => Pet) public petDetails; // mining tokens mapping(uint256 => uint256) public lastTimeMined; // Pet properties mapping(uint256 => uint256) public timeUntilStarving; mapping(uint256 => uint256) public petScore; mapping(uint256 => bool) public petDead; mapping(uint256 => uint256) public timePetBorn; // items/benefits for the PET could be anything in the future. mapping(uint256 => uint256) public itemPrice; mapping(uint256 => uint256) public itemPoints; mapping(uint256 => string) public itemName; mapping(uint256 => uint256) public itemTimeExtension; mapping(uint256 => mapping(address => address)) public careTaker; mapping(address => mapping(uint256 => bool)) public isNftInTheGame; //keeps track if nft already played mapping(address => mapping(uint256 => uint256)) public nftToId; //keeps track if nft already played uint256 public feesEarned; using CountersUpgradeable for CountersUpgradeable.Counter; CountersUpgradeable.Counter private _tokenIds; CountersUpgradeable.Counter private _itemIds; event Mined(uint256 nftId, uint256 reward, address recipient); event BuyAccessory( uint256 nftId, uint256 itemId, uint256 amount, uint256 itemTimeExtension, address buyer ); event Fatalize(uint256 opponentId, uint256 nftId, address killer); event NewPlayer( address nftAddress, uint256 nftId, uint256 playerId, address owner ); event Bonk( uint256 attacker, uint256 victim, uint256 winner, uint256 reward ); // Rewards algorithm uint256 public la; uint256 public lb; uint256 public ra; uint256 public rb; address public lastBonker; constructor() {} // // function initialize(address _token) public initializer { // __Ownable_init(); // token = IToken(_token); // la = 2; // lb = 2; // ra = 6; // rb = 7; // gas = 80000000000; // mooncats = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69; // PONDERWARE = 0xD342a4F0397B4268e6adce89b9B88C746AFA85Ee; // MUSE_DAO = 0x6fBa46974b2b1bEfefA034e236A32e1f10C5A148; // MUSE_DEVS = 0x4B5922ABf25858d012d12bb1184e5d3d0B6D6BE4; // supportedNfts[mooncats] = true; // } modifier isAllowed(uint256 _id) { Pet memory _pet = petDetails[_id]; address ownerOf = IERC721Upgradeable(_pet.nft).ownerOf(_pet.id); require( ownerOf == msg.sender || careTaker[_id][ownerOf] == msg.sender, "!owner" ); _; } // GAME ACTIONS //can mine once every 24 hours per token. function claimMiningRewards(uint256 nftId) public isAllowed(nftId) { lastGas = tx.gasprice; require(isPetSafe(nftId), "Your pet is starving, you can't mine"); require( block.timestamp >= lastTimeMined[nftId] + 1 days || lastTimeMined[nftId] == 0, "Current timestamp is over the limit to claim the tokens" ); //reset last start mined so can't remine and cheat lastTimeMined[nftId] = block.timestamp; uint256 _reward = getRewards(nftId); // 10% fees are for dev/dao/projects token.mint(msg.sender, _reward); emit Mined(nftId, _reward, msg.sender); } // Buy accesory to the VNFT function buyAccesory(uint256 nftId, uint256 itemId) public { require(!petDead[nftId], "ded pet"); uint256 amount = itemPrice[itemId]; require(amount > 0, "item does not exist"); // recalculate time until starving timeUntilStarving[nftId] = block.timestamp + itemTimeExtension[itemId]; petScore[nftId] += itemPoints[itemId]; token.burnFrom(msg.sender, amount); feesEarned += amount / 10; emit BuyAccessory( nftId, itemId, amount, itemTimeExtension[itemId], msg.sender ); } function feedMultiple(uint256[] calldata ids, uint256[] calldata itemIds) external { for (uint256 i = 0; i < ids.length; i++) { buyAccesory(ids[i], itemIds[i]); } } function claimMultiple(uint256[] calldata ids) external { for (uint256 i = 0; i < ids.length; i++) { claimMiningRewards(ids[i]); } } function bonk(uint256 _victim, uint256 _attacker) public isAllowed(_attacker) { require(isPetSafe(_victim), "Victim pet is starving, you can't mine"); require(isPetSafe(_attacker), "Your pet is starving, you can't mine"); require(lastBonker != msg.sender, "Can't bonk again"); require( lastTimeMined[_victim] + 1 minutes >= block.timestamp, "Can't bonk" ); lastBonker = msg.sender; // only bonking allowed when gas price is cheap? require(tx.gasprice <= gas, "!gas high"); Pet memory victimPet = petDetails[_victim]; address victimOwner = IERC721Upgradeable(victimPet.nft).ownerOf( victimPet.id ); require(msg.sender != victimOwner, "forbidden"); uint256 reward = ((level(_attacker) + level(_victim)) * 10) / 100; uint256 chanceOfAttack = randomNumber(_victim * _attacker, 100); if (chanceOfAttack <= 80) { //the attacker win 80% of time token.mint(msg.sender, reward * 10**18); } else { // the defender win 19% token.mint(victimOwner, reward * 10**18); } emit Bonk( _attacker, _victim, chanceOfAttack <= 80 ? _attacker : _victim, reward ); } //TOOD DECIDE FATALITY function fatality(uint256 _deadId, uint256 _tokenId) external { require( !isPetSafe(_deadId) && tx.gasprice <= gas && //inspired by NFT GAS by 0Xmons petDead[_deadId] == false, "The PET has to be starved or gas below ${gas} to claim his points" ); petScore[_tokenId] = petScore[_tokenId] + (((petScore[_deadId] * (20)) / (100))); petScore[_deadId] = 0; petDead[_deadId] = true; emit Fatalize(_deadId, _tokenId, msg.sender); } function getCareTaker(uint256 _tokenId, address _owner) public view returns (address) { return (careTaker[_tokenId][_owner]); } function setCareTaker( uint256 _tokenId, address _careTaker, bool clearCareTaker ) external isAllowed(_tokenId) { if (clearCareTaker) { delete careTaker[_tokenId][msg.sender]; } else { careTaker[_tokenId][msg.sender] = _careTaker; } } // requires approval function giveLife(address nft, uint256 _id) external { require(IERC721Upgradeable(nft).ownerOf(_id) == msg.sender, "!OWNER"); require( !isNftInTheGame[nft][_id], "this nft was already registered can't again" ); require(supportedNfts[nft], "!forbidden"); uint256 newId = _tokenIds.current(); // set the pet struct petDetails[newId] = Pet(nft, _id); nftToId[nft][_id] = newId; isNftInTheGame[nft][_id] = true; timeUntilStarving[newId] = block.timestamp + 3 days; //start with 3 days of life. timePetBorn[newId] = block.timestamp; emit NewPlayer(nft, _id, newId, msg.sender); _tokenIds.increment(); } // GETTERS // check that pet didn't starve function isPetSafe(uint256 _nftId) public view returns (bool) { uint256 _timeUntilStarving = timeUntilStarving[_nftId]; if ( (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) || lastGas >= gas ) { return true; } else { return false; } } // GETTERS function getPetInfo(uint256 _nftId) public view returns ( uint256 _pet, bool _isStarving, uint256 _score, uint256 _level, uint256 _expectedReward, uint256 _timeUntilStarving, uint256 _lastTimeMined, uint256 _timepetBorn, address _owner, address _token, uint256 _tokenId, bool _isAlive ) { Pet memory thisPet = petDetails[_nftId]; _pet = _nftId; _isStarving = !this.isPetSafe(_nftId); _score = petScore[_nftId]; _level = level(_nftId); _expectedReward = getRewards(_nftId); _timeUntilStarving = timeUntilStarving[_nftId]; _lastTimeMined = lastTimeMined[_nftId]; _timepetBorn = timePetBorn[_nftId]; _owner = IERC721Upgradeable(thisPet.nft).ownerOf(thisPet.id); _token = petDetails[_nftId].nft; _tokenId = petDetails[_nftId].id; _isAlive = !petDead[_nftId]; } // get the level the pet is on to calculate the token reward function getRewards(uint256 tokenId) public view returns (uint256) { // This is the formula to get token rewards R(level)=(level)*6/7+6 uint256 _level = level(tokenId); if (_level == 1) { return 6 ether; } _level = (_level * 1 ether * ra) / rb; return (_level + 5 ether); } // get the level the pet is on to calculate points function level(uint256 tokenId) public view returns (uint256) { // This is the formula L(x) = 2 * sqrt(x * 2) uint256 _score = petScore[tokenId] / 100; if (_score == 0) { return 1; } uint256 _level = sqrtu(_score * la); return (_level * lb); } // ADMIN function editCurves( uint256 _la, uint256 _lb, uint256 _ra, uint256 _rb ) external onlyOwner { la = _la; lb = _lb; ra = _ra; rb = _rb; } // edit specific item in case token goes up in value and the price for items gets to expensive for normal users. function editItem( uint256 _id, uint256 _price, uint256 _points, string calldata _name, uint256 _timeExtension ) external onlyOwner { itemPrice[_id] = _price; itemPoints[_id] = _points; itemName[_id] = _name; itemTimeExtension[_id] = _timeExtension; } // to support more projects function setSupported(address _nft, bool isSupported) public onlyOwner { supportedNfts[_nft] = isSupported; } function setGas(uint256 _gas) public onlyOwner { gas = _gas; } // add items/accessories function createItem( string calldata name, uint256 price, uint256 points, uint256 timeExtension ) external onlyOwner { _itemIds.increment(); uint256 newItemId = _itemIds.current(); itemName[newItemId] = name; itemPrice[newItemId] = price; itemPoints[newItemId] = points; itemTimeExtension[newItemId] = timeExtension; } function changeEarners(address _newAddress) public { require( msg.sender == MUSE_DEVS || msg.sender == PONDERWARE, "!forbidden" ); if (msg.sender == MUSE_DEVS) { MUSE_DEVS = _newAddress; } else if (msg.sender == PONDERWARE) { PONDERWARE = _newAddress; } } // anyone can call this function claimEarnings() public { token.mint(address(this), feesEarned); feesEarned = 0; uint256 balance = token.balanceOf(address(this)); token.transfer(PONDERWARE, balance / 3); token.transfer(MUSE_DAO, balance / 3); token.transfer(MUSE_DEVS, balance / 3); } function randomNumber(uint256 seed, uint256 max) public view returns (uint256 _randomNumber) { uint256 n = 0; unchecked { for (uint256 i = 0; i < 5; i++) { n += uint256( keccak256( abi.encodePacked(blockhash(block.number - i - 1), seed) ) ); } } return (n) % max; } function sqrtu(uint256 x) private pure returns (uint128) { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @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; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @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); }
items/benefits for the PET could be anything in the future.
mapping(uint256 => uint256) public itemPrice;
1,138,266
[ 1, 3319, 19, 70, 4009, 18352, 364, 326, 453, 1584, 3377, 506, 6967, 316, 326, 3563, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 761, 5147, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract euroteambet { struct team { string teamName; mapping(address => uint) bet; uint totalBet; } team[] public euroTeams; bool winningTeamDefined; uint winningTeam; /** Bets close at the opening day of the EuroCup: 10 June 2016 **/ uint startCompetitionTime; /** Overall amount bet **/ uint public globalBet; /** Define the creator and fees collected **/ address creator; uint feeCollected; /** * Constructor: Defines team and creator */ function euroteambet() { // Define the Teams team memory toCreate; // Post a dummy team to ensure the actual range is from 1 to 24 and not 0 to 23. toCreate.teamName = &#39;&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Albania&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Austria&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Belgium&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Croatia&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Czech Republic&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;England&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;France&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Germany&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Hungary&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Iceland&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Italy&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Nothern Ireland&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Poland&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Portugal&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Republic of Ireland&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Romania&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Russia&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Slovakia&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Spain&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Sweden&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Switzerland&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Turkey&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Ukraine&#39;; euroTeams.push(toCreate); toCreate.teamName = &#39;Wales&#39;; euroTeams.push(toCreate); creator = msg.sender; winningTeamDefined = false; // Euro Cup starts in 4 days startCompetitionTime = block.timestamp + (60 * 60 * 24) * 4; } event BetFromTransaction(address indexed from, uint value); event CollectFromTransaction(address indexed from, uint value); event BetClosedNoWinningTeam(address indexed from, uint value); /** * Catch-All Function: Un case of transaction received going though a Contract Function * 1: Check if bets are still open * 2: Check if the bet is more than 0.1 ETH * 3: Divided by 1000000000000000 to have an integer (0.016 Eth to 16) and call betOnATeam * If the EeasyBet value is not correct (possible value 1 to 24), it will be throw in BetOnAteam function * 4: Check if the winning team as been defined */ function () { if (startCompetitionTime >= block.timestamp) { if (msg.value >= 100 finney) { BetFromTransaction(msg.sender, msg.value); betOnATeam((msg.value % 100 finney) / 1000000000000000); } else { msg.sender.send(msg.value); return; } } else if (winningTeamDefined == true) { CollectFromTransaction(msg.sender, msg.value); collectEarnings(); } else { BetClosedNoWinningTeam(msg.sender, msg.value); if(msg.value > 0){ msg.sender.send(msg.value); } return; } } /** * Used to defined the winner of the Tournament * 1: The winning team is updated * 2: All amount invested are gathered in globalBet * 3: All balances of the winning team updated proportionally to the amount invested * * param {uint teamWinningName The identifier of the team winning */ function setWinner(uint teamWinningID) { // Check if the sender is the creator and if the tournament has ended if (msg.sender == creator) { winningTeam = teamWinningID; winningTeamDefined = true; } else { if(msg.value > 0){ msg.sender.send(msg.value); } return; } } event BetOnATeam(address indexed from, uint indexed id, uint value); /** * Used to bet on the winner of the Tournament * 1: Check if bets are still open * 2: Check if the bet is more than 0.1 ETH * 3: Check if the id of the team is correct (possible value 1 to 24) * param {uint} id The identifier of the team to bet on */ function betOnATeam(uint id) { if (startCompetitionTime >= block.timestamp && msg.value >= 100 finney && id >= 1 && id <= 24) { uint amount = msg.value; // Collect 3% Fee feeCollected += (amount * 3 / 100); amount -= (amount * 3 / 100); BetOnATeam(msg.sender, id, amount); euroTeams[id].bet[msg.sender] += amount; euroTeams[id].totalBet += amount; globalBet += amount; } else { if(msg.value > 0){ msg.sender.send(msg.value); } return; } } /** * Check earnings for a specific address * * param address toCheck Address to check its earnings * return uint Amount earned */ function checkEarnings(address toCheck) returns (uint) { if(msg.value > 0){ msg.sender.send(msg.value); } if (winningTeamDefined == true) { return (globalBet * (euroTeams[winningTeam].bet[toCheck] / euroTeams[winningTeam].totalBet)); } else { return 0; } } /** * Only allowed the withdrawals of the fund once the Winning team is updated */ function collectEarnings() { if(msg.value > 0){ msg.sender.send(msg.value); } if (winningTeamDefined == true) { uint earnings = (globalBet * (euroTeams[winningTeam].bet[msg.sender] / euroTeams[winningTeam].totalBet)); msg.sender.send(earnings); euroTeams[winningTeam].bet[msg.sender] = 0; } else { return; } } /** * Allow the creator of the game to send balance * * param address toSend Address to receive its earnings */ function sendEarnings(address toSend) { if(msg.value > 0){ msg.sender.send(msg.value); } if (msg.sender == creator && winningTeamDefined == true) { uint earnings = (globalBet * (euroTeams[winningTeam].bet[toSend] / euroTeams[winningTeam].totalBet)); toSend.send(earnings); euroTeams[winningTeam].bet[toSend] = 0; } else { return; } } /** * Allow the creator to collect the 3% Fee */ function collectFee() { msg.sender.send(msg.value); if (msg.sender == creator) { creator.send(feeCollected); feeCollected = 0; } else { return; } } }
* Used to defined the winner of the Tournament 1: The winning team is updated 2: All amount invested are gathered in globalBet 3: All balances of the winning team updated proportionally to the amount invested param {uint teamWinningName The identifier of the team winning/ Check if the sender is the creator and if the tournament has ended
function setWinner(uint teamWinningID) { if (msg.sender == creator) { winningTeam = teamWinningID; winningTeamDefined = true; if(msg.value > 0){ msg.sender.send(msg.value); } return; } } event BetOnATeam(address indexed from, uint indexed id, uint value);
1,035,042
[ 1, 6668, 358, 2553, 326, 5657, 1224, 434, 326, 2974, 30751, 404, 30, 1021, 5657, 2093, 5927, 353, 3526, 576, 30, 4826, 3844, 2198, 3149, 854, 11090, 329, 316, 2552, 38, 278, 890, 30, 4826, 324, 26488, 434, 326, 5657, 2093, 5927, 3526, 23279, 1230, 358, 326, 3844, 2198, 3149, 579, 1377, 288, 11890, 225, 5927, 18049, 2093, 461, 225, 1021, 2756, 434, 326, 5927, 5657, 2093, 19, 2073, 309, 326, 5793, 353, 326, 11784, 471, 309, 326, 358, 30751, 711, 16926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 444, 59, 7872, 12, 11890, 5927, 18049, 2093, 734, 13, 288, 203, 202, 202, 430, 261, 3576, 18, 15330, 422, 11784, 13, 288, 203, 1082, 202, 8082, 2093, 8689, 273, 5927, 18049, 2093, 734, 31, 203, 1082, 202, 8082, 2093, 8689, 8116, 273, 638, 31, 203, 1082, 202, 430, 12, 3576, 18, 1132, 405, 374, 15329, 203, 9506, 202, 3576, 18, 15330, 18, 4661, 12, 3576, 18, 1132, 1769, 203, 1082, 202, 97, 203, 1082, 202, 2463, 31, 203, 202, 202, 97, 203, 202, 97, 203, 203, 203, 202, 2575, 605, 278, 1398, 789, 3820, 12, 2867, 8808, 628, 16, 2254, 8808, 612, 16, 2254, 460, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x72df14329E29F00A3866794F82723c85c6B36dCC/sources/Debt.sol
* @return set the contractUrl/
function setContractUrl(string memory url) public onlyOwner returns (bool) { _contractUrl = url; return true; }
2,602,014
[ 1, 2463, 444, 326, 6835, 1489, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 8924, 1489, 12, 1080, 3778, 880, 13, 1071, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 389, 16351, 1489, 273, 880, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * @author Valentin Mueller <https://github.com/ValentinFFM> */ // SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.7.0; // Experimental function is necessary to allow mappings with structs. pragma experimental ABIEncoderV2; // Import of Smart Contract "User" to interact with the functionalities of it import "./User.sol"; /** The Smart Contract Prescriptions is responsible for storing the information of all prescriptions. Furthermore it provides all necessary functions to interact with prescriptions. */ contract Prescriptions { address public verifying_institution; User UserContract; uint prescription_id; // Assigns the creator of the smart contract as verifying institution and sets the first prescription_id. constructor () public { verifying_institution = msg.sender; prescription_id = 0; } // Defining struct that contains all variables that are needed for a prescription. struct Prescription { address physician; address insured; address pharmacist; bool pharmacistEqualsInsured; string status; string medicine_name; string medicine_amount; } // For every user group the public keys of the users are mapped to an array containing prescription-ids. mapping(address => uint[]) public prescriptionPhysician; mapping(address => uint[]) public prescriptionInsured; mapping(address => uint[]) public prescriptionPharmacist; // Mapping prescription-ids to the corresponding prescription struct. mapping(uint => Prescription) public prescription; // Function for connecting the Smart Contract user to the Smart Contract prescription. function establishConnectionToUserSmartContract(address smart_contract_key) public { require(msg.sender == verifying_institution, "Only the verify institution has the premission to connect prescription to user!"); UserContract = User(smart_contract_key); } function newPrescription(Prescription memory prescription_) public{ require(UserContract.checkVerification('physician', msg.sender) == true, "You don't have the premission to create a prescription!"); require(UserContract.checkVerification('insured', prescription_.insured) == true, "This insured is not registered or verified!"); prescription[prescription_id] = Prescription(prescription_.physician, prescription_.insured, prescription_.pharmacist, prescription_.pharmacistEqualsInsured, 'Patient', prescription_.medicine_name, prescription_.medicine_amount); prescriptionPhysician[prescription_.physician].push(prescription_id); prescriptionInsured[prescription_.insured].push(prescription_id); prescription_id = prescription_id + 1; } function transferPrescriptionToPharmacist(uint prescription_id_, address pharmacist) public { Prescription memory prescription_ = prescription[prescription_id_]; require(msg.sender == prescription_.insured, "The prescription you try to transfer is not your prescription!"); require(UserContract.checkVerification('insured', prescription_.insured) == true, "You don't have the premission to transfer a prescription!"); require(UserContract.checkVerification('pharmacist', pharmacist) == true, "This pharmacist is not registered or verified!"); prescription[prescription_id_] = Prescription(prescription_.physician, prescription_.insured, pharmacist, prescription_.pharmacistEqualsInsured, 'Pharmacist', prescription_.medicine_name, prescription_.medicine_amount); prescriptionPharmacist[pharmacist].push(prescription_id_); } function redeemPrescription(uint prescription_id_) public { Prescription memory prescription_ = prescription[prescription_id_]; require(UserContract.checkVerification('pharmacist', msg.sender) == true, "You don't have the premission to redeem a prescription!"); require(msg.sender == prescription_.pharmacist, "The prescription you try to redeem is not your prescription!"); prescription[prescription_id_] = Prescription(prescription_.physician, prescription_.insured, prescription_.pharmacist, prescription_.pharmacistEqualsInsured, 'Redeemed', prescription_.medicine_name, prescription_.medicine_amount); } function getPrescription(uint prescription_id_) public returns (Prescription memory){ return prescription[prescription_id_]; } function getPhysicianPrescriptionsIDs(address public_key) public returns (uint[] memory){ return prescriptionPhysician[public_key]; } function getInsuredPrescriptionsIDs(address public_key) public returns (uint[] memory){ return prescriptionInsured[public_key]; } function getPharmacistPrescriptionsIDs(address public_key) public returns (uint[] memory){ return prescriptionPharmacist[public_key]; } }
For every user group the public keys of the users are mapped to an array containing prescription-ids.
mapping(address => uint[]) public prescriptionPhysician;
5,546,460
[ 1, 1290, 3614, 729, 1041, 326, 1071, 1311, 434, 326, 3677, 854, 5525, 358, 392, 526, 4191, 4075, 24136, 17, 2232, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 63, 5717, 1071, 4075, 24136, 3731, 1900, 335, 2779, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x9460b380c57F65e8AFc4bA3518F643A526640F26/sources/contracts/protocol/libraries/math/PercentageMath.sol
* @title PercentageMath library @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. If a value is >=.5, will be rounded up, otherwise rounded down./ Maximum percentage factor (100.00%) Half percentage factor (50.00%)
library PercentageMath { uint256 internal constant PERCENTAGE_FACTOR = 1e4; uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4; function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256 result) pragma solidity ^0.8.0; { assembly { if iszero( or( iszero(percentage), iszero( gt( value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR ) } } { assembly { if iszero( or( iszero(percentage), iszero( gt( value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR ) } } { assembly { if iszero( or( iszero(percentage), iszero( gt( value, div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, percentage), HALF_PERCENTAGE_FACTOR), PERCENTAGE_FACTOR ) } } function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) { assembly { if or( iszero(percentage), iszero( iszero( gt( value, div( sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR ) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage ) } } function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) { assembly { if or( iszero(percentage), iszero( iszero( gt( value, div( sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR ) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage ) } } function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256 result) { assembly { if or( iszero(percentage), iszero( iszero( gt( value, div( sub(not(0), div(percentage, 2)), PERCENTAGE_FACTOR ) ) ) ) ) { revert(0, 0) } result := div( add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)), percentage ) } } }
4,203,289
[ 1, 16397, 10477, 5313, 225, 28805, 4186, 358, 3073, 11622, 20882, 225, 21198, 1023, 854, 2553, 635, 805, 598, 576, 15105, 434, 6039, 261, 6625, 18, 713, 2934, 1021, 6039, 353, 17710, 635, 10950, 19666, 2833, 67, 26835, 225, 25938, 854, 16729, 18, 971, 279, 460, 353, 1545, 18, 25, 16, 903, 506, 16729, 731, 16, 3541, 16729, 2588, 18, 19, 18848, 11622, 5578, 261, 6625, 18, 713, 9, 13, 670, 6186, 11622, 5578, 261, 3361, 18, 713, 9, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 21198, 410, 10477, 288, 203, 565, 2254, 5034, 2713, 5381, 10950, 19666, 2833, 67, 26835, 273, 404, 73, 24, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 670, 21497, 67, 3194, 19666, 2833, 67, 26835, 273, 374, 18, 25, 73, 24, 31, 203, 203, 565, 445, 5551, 27860, 12, 11890, 5034, 460, 16, 2254, 5034, 11622, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 11890, 5034, 563, 13, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 288, 203, 3639, 19931, 288, 203, 5411, 309, 353, 7124, 12, 203, 7734, 578, 12, 203, 10792, 353, 7124, 12, 18687, 3631, 203, 10792, 353, 7124, 12, 203, 13491, 9879, 12, 203, 18701, 460, 16, 203, 18701, 3739, 12, 1717, 12, 902, 12, 20, 3631, 670, 21497, 67, 3194, 19666, 2833, 67, 26835, 3631, 11622, 13, 203, 13491, 262, 203, 10792, 262, 203, 7734, 262, 203, 5411, 262, 288, 203, 7734, 15226, 12, 20, 16, 374, 13, 203, 5411, 289, 203, 203, 5411, 563, 519, 3739, 12, 203, 7734, 527, 12, 16411, 12, 1132, 16, 11622, 3631, 670, 21497, 67, 3194, 19666, 2833, 67, 26835, 3631, 203, 7734, 10950, 19666, 2833, 67, 26835, 203, 5411, 262, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 19931, 288, 203, 5411, 309, 353, 7124, 12, 203, 7734, 578, 12, 203, 10792, 353, 7124, 12, 18687, 3631, 203, 10792, 353, 7124, 12, 203, 13491, 9879, 12, 203, 18701, 460, 16, 203, 18701, 3739, 12, 1717, 12, 902, 12, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; pragma experimental ABIEncoderV2; // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardEvents.sol /// @title Witnet Request Board emitting events interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardEvents { /// Emitted when a Witnet Data Request is posted to the WRB. event PostedRequest(uint256 queryId, address from); /// Emitted when a Witnet-solved result is reported to the WRB. event PostedResult(uint256 queryId, address from); /// Emitted when all data related to given query is deleted from the WRB. event DeletedQuery(uint256 queryId, address from); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardReporter.sol /// @title The Witnet Request Board Reporter interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardReporter { /// Reports the Witnet-provided result to a previously posted request. /// @dev Will assume `block.timestamp` as the timestamp at which the request was solved. /// @dev Fails if: /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique identifier of the data request. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, bytes32 _drTxHash, bytes calldata _result) external; /// Reports the Witnet-provided result to a previously posted request. /// @dev Fails if: /// @dev - called from unauthorized address; /// @dev - the `_queryId` is not in 'Posted' status. /// @dev - provided `_drTxHash` is zero; /// @dev - length of provided `_result` is zero. /// @param _queryId The unique query identifier /// @param _timestamp The timestamp of the solving tally transaction in Witnet. /// @param _drTxHash The hash of the solving tally transaction in Witnet. /// @param _result The result itself as bytes. function reportResult(uint256 _queryId, uint256 _timestamp, bytes32 _drTxHash, bytes calldata _result) external; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequest.sol /// @title The Witnet Data Request basic interface. /// @author The Witnet Foundation. interface IWitnetRequest { /// A `IWitnetRequest` is constructed around a `bytes` value containing /// a well-formed Witnet Data Request using Protocol Buffers. function bytecode() external view returns (bytes memory); /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. function hash() external view returns (bytes32); } // File: node_modules\witnet-solidity-bridge\contracts\libs\Witnet.sol library Witnet { /// @notice Witnet function that computes the hash of a CBOR-encoded Data Request. /// @param _bytecode CBOR-encoded RADON. function hash(bytes memory _bytecode) internal pure returns (bytes32) { return sha256(_bytecode); } /// Struct containing both request and response data related to every query posted to the Witnet Request Board struct Query { Request request; Response response; } /// Possible status of a Witnet query. enum QueryStatus { Unknown, Posted, Reported, Deleted } /// Data kept in EVM-storage for every Request posted to the Witnet Request Board. struct Request { IWitnetRequest addr; // The contract containing the Data Request which execution has been requested. address requester; // Address from which the request was posted. bytes32 hash; // Hash of the Data Request whose execution has been requested. uint256 gasprice; // Minimum gas price the DR resolver should pay on the solving tx. uint256 reward; // Escrowed reward to be paid to the DR resolver. } /// Data kept in EVM-storage containing Witnet-provided response metadata and result. struct Response { address reporter; // Address from which the result was reported. uint256 timestamp; // Timestamp of the Witnet-provided result. bytes32 drTxHash; // Hash of the Witnet transaction that solved the queried Data Request. bytes cborBytes; // Witnet-provided result CBOR-bytes to the queried Data Request. } /// Data struct containing the Witnet-provided result to a Data Request. struct Result { bool success; // Flag stating whether the request could get solved successfully, or not. CBOR value; // Resulting value, in CBOR-serialized bytes. } /// Data struct following the RFC-7049 standard: Concise Binary Object Representation. struct CBOR { Buffer buffer; uint8 initialByte; uint8 majorType; uint8 additionalInformation; uint64 len; uint64 tag; } /// Iterable bytes buffer. struct Buffer { bytes data; uint32 cursor; } /// Witnet error codes table. enum ErrorCodes { // 0x00: Unknown error. Something went really bad! Unknown, // Script format errors /// 0x01: At least one of the source scripts is not a valid CBOR-encoded value. SourceScriptNotCBOR, /// 0x02: The CBOR value decoded from a source script is not an Array. SourceScriptNotArray, /// 0x03: The Array value decoded form a source script is not a valid Data Request. SourceScriptNotRADON, /// Unallocated ScriptFormat0x04, ScriptFormat0x05, ScriptFormat0x06, ScriptFormat0x07, ScriptFormat0x08, ScriptFormat0x09, ScriptFormat0x0A, ScriptFormat0x0B, ScriptFormat0x0C, ScriptFormat0x0D, ScriptFormat0x0E, ScriptFormat0x0F, // Complexity errors /// 0x10: The request contains too many sources. RequestTooManySources, /// 0x11: The script contains too many calls. ScriptTooManyCalls, /// Unallocated Complexity0x12, Complexity0x13, Complexity0x14, Complexity0x15, Complexity0x16, Complexity0x17, Complexity0x18, Complexity0x19, Complexity0x1A, Complexity0x1B, Complexity0x1C, Complexity0x1D, Complexity0x1E, Complexity0x1F, // Operator errors /// 0x20: The operator does not exist. UnsupportedOperator, /// Unallocated Operator0x21, Operator0x22, Operator0x23, Operator0x24, Operator0x25, Operator0x26, Operator0x27, Operator0x28, Operator0x29, Operator0x2A, Operator0x2B, Operator0x2C, Operator0x2D, Operator0x2E, Operator0x2F, // Retrieval-specific errors /// 0x30: At least one of the sources could not be retrieved, but returned HTTP error. HTTP, /// 0x31: Retrieval of at least one of the sources timed out. RetrievalTimeout, /// Unallocated Retrieval0x32, Retrieval0x33, Retrieval0x34, Retrieval0x35, Retrieval0x36, Retrieval0x37, Retrieval0x38, Retrieval0x39, Retrieval0x3A, Retrieval0x3B, Retrieval0x3C, Retrieval0x3D, Retrieval0x3E, Retrieval0x3F, // Math errors /// 0x40: Math operator caused an underflow. Underflow, /// 0x41: Math operator caused an overflow. Overflow, /// 0x42: Tried to divide by zero. DivisionByZero, /// Unallocated Math0x43, Math0x44, Math0x45, Math0x46, Math0x47, Math0x48, Math0x49, Math0x4A, Math0x4B, Math0x4C, Math0x4D, Math0x4E, Math0x4F, // Other errors /// 0x50: Received zero reveals NoReveals, /// 0x51: Insufficient consensus in tally precondition clause InsufficientConsensus, /// 0x52: Received zero commits InsufficientCommits, /// 0x53: Generic error during tally execution TallyExecution, /// Unallocated OtherError0x54, OtherError0x55, OtherError0x56, OtherError0x57, OtherError0x58, OtherError0x59, OtherError0x5A, OtherError0x5B, OtherError0x5C, OtherError0x5D, OtherError0x5E, OtherError0x5F, /// 0x60: Invalid reveal serialization (malformed reveals are converted to this value) MalformedReveal, /// Unallocated OtherError0x61, OtherError0x62, OtherError0x63, OtherError0x64, OtherError0x65, OtherError0x66, OtherError0x67, OtherError0x68, OtherError0x69, OtherError0x6A, OtherError0x6B, OtherError0x6C, OtherError0x6D, OtherError0x6E, OtherError0x6F, // Access errors /// 0x70: Tried to access a value from an index using an index that is out of bounds ArrayIndexOutOfBounds, /// 0x71: Tried to access a value from a map using a key that does not exist MapKeyNotFound, /// Unallocated OtherError0x72, OtherError0x73, OtherError0x74, OtherError0x75, OtherError0x76, OtherError0x77, OtherError0x78, OtherError0x79, OtherError0x7A, OtherError0x7B, OtherError0x7C, OtherError0x7D, OtherError0x7E, OtherError0x7F, OtherError0x80, OtherError0x81, OtherError0x82, OtherError0x83, OtherError0x84, OtherError0x85, OtherError0x86, OtherError0x87, OtherError0x88, OtherError0x89, OtherError0x8A, OtherError0x8B, OtherError0x8C, OtherError0x8D, OtherError0x8E, OtherError0x8F, OtherError0x90, OtherError0x91, OtherError0x92, OtherError0x93, OtherError0x94, OtherError0x95, OtherError0x96, OtherError0x97, OtherError0x98, OtherError0x99, OtherError0x9A, OtherError0x9B, OtherError0x9C, OtherError0x9D, OtherError0x9E, OtherError0x9F, OtherError0xA0, OtherError0xA1, OtherError0xA2, OtherError0xA3, OtherError0xA4, OtherError0xA5, OtherError0xA6, OtherError0xA7, OtherError0xA8, OtherError0xA9, OtherError0xAA, OtherError0xAB, OtherError0xAC, OtherError0xAD, OtherError0xAE, OtherError0xAF, OtherError0xB0, OtherError0xB1, OtherError0xB2, OtherError0xB3, OtherError0xB4, OtherError0xB5, OtherError0xB6, OtherError0xB7, OtherError0xB8, OtherError0xB9, OtherError0xBA, OtherError0xBB, OtherError0xBC, OtherError0xBD, OtherError0xBE, OtherError0xBF, OtherError0xC0, OtherError0xC1, OtherError0xC2, OtherError0xC3, OtherError0xC4, OtherError0xC5, OtherError0xC6, OtherError0xC7, OtherError0xC8, OtherError0xC9, OtherError0xCA, OtherError0xCB, OtherError0xCC, OtherError0xCD, OtherError0xCE, OtherError0xCF, OtherError0xD0, OtherError0xD1, OtherError0xD2, OtherError0xD3, OtherError0xD4, OtherError0xD5, OtherError0xD6, OtherError0xD7, OtherError0xD8, OtherError0xD9, OtherError0xDA, OtherError0xDB, OtherError0xDC, OtherError0xDD, OtherError0xDE, OtherError0xDF, // Bridge errors: errors that only belong in inter-client communication /// 0xE0: Requests that cannot be parsed must always get this error as their result. /// However, this is not a valid result in a Tally transaction, because invalid requests /// are never included into blocks and therefore never get a Tally in response. BridgeMalformedRequest, /// 0xE1: Witnesses exceeds 100 BridgePoorIncentives, /// 0xE2: The request is rejected on the grounds that it may cause the submitter to spend or stake an /// amount of value that is unjustifiably high when compared with the reward they will be getting BridgeOversizedResult, /// Unallocated OtherError0xE3, OtherError0xE4, OtherError0xE5, OtherError0xE6, OtherError0xE7, OtherError0xE8, OtherError0xE9, OtherError0xEA, OtherError0xEB, OtherError0xEC, OtherError0xED, OtherError0xEE, OtherError0xEF, OtherError0xF0, OtherError0xF1, OtherError0xF2, OtherError0xF3, OtherError0xF4, OtherError0xF5, OtherError0xF6, OtherError0xF7, OtherError0xF8, OtherError0xF9, OtherError0xFA, OtherError0xFB, OtherError0xFC, OtherError0xFD, OtherError0xFE, // This should not exist: /// 0xFF: Some tally error is not intercepted but should UnhandledIntercept } } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardRequestor.sol /// @title Witnet Requestor Interface /// @notice It defines how to interact with the Witnet Request Board in order to: /// - request the execution of Witnet Radon scripts (data request); /// - upgrade the resolution reward of any previously posted request, in case gas price raises in mainnet; /// - read the result of any previously posted request, eventually reported by the Witnet DON. /// - remove from storage all data related to past and solved data requests, and results. /// @author The Witnet Foundation. interface IWitnetRequestBoardRequestor { /// Retrieves a copy of all Witnet-provided data related to a previously posted request, removing the whole query from the WRB storage. /// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to /// @dev the one that actually posted the given request. /// @param _queryId The unique query identifier. function deleteQuery(uint256 _queryId) external returns (Witnet.Response memory); /// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON. /// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided /// result to this request. /// @dev Fails if: /// @dev - provided reward is too low. /// @dev - provided script is zero address. /// @dev - provided script bytecode is empty. /// @param _addr The address of the IWitnetRequest contract that can provide the actual Data Request bytecode. /// @return _queryId An unique query identifier. function postRequest(IWitnetRequest _addr) external payable returns (uint256 _queryId); /// Increments the reward of a previously posted request by adding the transaction value to it. /// @dev Updates request `gasPrice` in case this method is called with a higher /// @dev gas price value than the one used in previous calls to `postRequest` or /// @dev `upgradeReward`. /// @dev Fails if the `_queryId` is not in 'Posted' status. /// @dev Fails also in case the request `gasPrice` is increased, and the new /// @dev reward value gets below new recalculated threshold. /// @param _queryId The unique query identifier. function upgradeReward(uint256 _queryId) external payable; } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestBoardView.sol /// @title Witnet Request Board info interface. /// @author The Witnet Foundation. interface IWitnetRequestBoardView { /// Estimates the amount of reward we need to insert for a given gas price. /// @param _gasPrice The gas price for which we need to calculate the rewards. function estimateReward(uint256 _gasPrice) external view returns (uint256); /// Returns next query id to be generated by the Witnet Request Board. function getNextQueryId() external view returns (uint256); /// Gets the whole Query data contents, if any, no matter its current status. function getQueryData(uint256 _queryId) external view returns (Witnet.Query memory); /// Gets current status of given query. function getQueryStatus(uint256 _queryId) external view returns (Witnet.QueryStatus); /// Retrieves the whole `Witnet.Request` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequest(uint256 _queryId) external view returns (Witnet.Request memory); /// Retrieves the serialized bytecode of a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestBytecode(uint256 _queryId) external view returns (bytes memory); /// Retrieves the gas price that any assigned reporter will have to pay when reporting result /// to the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestGasPrice(uint256 _queryId) external view returns (uint256); /// Retrieves the reward currently set for the referred query. /// @dev Fails if the `_queryId` is not valid or, if it has been deleted, /// @dev or if the related script bytecode got changed after being posted. /// @param _queryId The unique query identifier. function readRequestReward(uint256 _queryId) external view returns (uint256); /// Retrieves the whole `Witnet.Response` record referred to a previously posted Witnet Data Request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponse(uint256 _queryId) external view returns (Witnet.Response memory); /// Retrieves the hash of the Witnet transaction hash that actually solved the referred query. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseDrTxHash(uint256 _queryId) external view returns (bytes32); /// Retrieves the address that reported the result to a previously-posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseReporter(uint256 _queryId) external view returns (address); /// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseResult(uint256 _queryId) external view returns (Witnet.Result memory); /// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON. /// @dev Fails if the `_queryId` is not in 'Reported' status. /// @param _queryId The unique query identifier. function readResponseTimestamp(uint256 _queryId) external view returns (uint256); } // File: node_modules\witnet-solidity-bridge\contracts\interfaces\IWitnetRequestParser.sol /// @title The Witnet interface for decoding Witnet-provided request to Data Requests. /// This interface exposes functions to check for the success/failure of /// a Witnet-provided result, as well as to parse and convert result into /// Solidity types suitable to the application level. /// @author The Witnet Foundation. interface IWitnetRequestParser { /// Decode raw CBOR bytes into a Witnet.Result instance. /// @param _cborBytes Raw bytes representing a CBOR-encoded value. /// @return A `Witnet.Result` instance. function resultFromCborBytes(bytes memory _cborBytes) external pure returns (Witnet.Result memory); /// Decode a CBOR value into a Witnet.Result instance. /// @param _cborValue An instance of `Witnet.CBOR`. /// @return A `Witnet.Result` instance. function resultFromCborValue(Witnet.CBOR memory _cborValue) external pure returns (Witnet.Result memory); /// Tell if a Witnet.Result is successful. /// @param _result An instance of Witnet.Result. /// @return `true` if successful, `false` if errored. function isOk(Witnet.Result memory _result) external pure returns (bool); /// Tell if a Witnet.Result is errored. /// @param _result An instance of Witnet.Result. /// @return `true` if errored, `false` if successful. function isError(Witnet.Result memory _result) external pure returns (bool); /// Decode a bytes value from a Witnet.Result as a `bytes` value. /// @param _result An instance of Witnet.Result. /// @return The `bytes` decoded from the Witnet.Result. function asBytes(Witnet.Result memory _result) external pure returns (bytes memory); /// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`. /// @param _result An instance of `Witnet.Result`. /// @return The `CBORValue.Error memory` decoded from the Witnet.Result. function asErrorCode(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes); /// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments. /// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function /// @param _result An instance of `Witnet.Result`. /// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message. function asErrorMessage(Witnet.Result memory _result) external pure returns (Witnet.ErrorCodes, string memory); /// Decode a raw error from a `Witnet.Result` as a `uint64[]`. /// @param _result An instance of `Witnet.Result`. /// @return The `uint64[]` raw error as decoded from the `Witnet.Result`. function asRawError(Witnet.Result memory _result) external pure returns(uint64[] memory); /// Decode a boolean value from a Witnet.Result as an `bool` value. /// @param _result An instance of Witnet.Result. /// @return The `bool` decoded from the Witnet.Result. function asBool(Witnet.Result memory _result) external pure returns (bool); /// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value. /// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values. /// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`. /// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asFixed16(Witnet.Result memory _result) external pure returns (int32); /// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asFixed16Array(Witnet.Result memory _result) external pure returns (int32[] memory); /// Decode a integer numeric value from a Witnet.Result as an `int128` value. /// @param _result An instance of Witnet.Result. /// @return The `int128` decoded from the Witnet.Result. function asInt128(Witnet.Result memory _result) external pure returns (int128); /// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value. /// @param _result An instance of Witnet.Result. /// @return The `int128[]` decoded from the Witnet.Result. function asInt128Array(Witnet.Result memory _result) external pure returns (int128[] memory); /// Decode a string value from a Witnet.Result as a `string` value. /// @param _result An instance of Witnet.Result. /// @return The `string` decoded from the Witnet.Result. function asString(Witnet.Result memory _result) external pure returns (string memory); /// Decode an array of string values from a Witnet.Result as a `string[]` value. /// @param _result An instance of Witnet.Result. /// @return The `string[]` decoded from the Witnet.Result. function asStringArray(Witnet.Result memory _result) external pure returns (string[] memory); /// Decode a natural numeric value from a Witnet.Result as a `uint64` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64` decoded from the Witnet.Result. function asUint64(Witnet.Result memory _result) external pure returns(uint64); /// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value. /// @param _result An instance of Witnet.Result. /// @return The `uint64[]` decoded from the Witnet.Result. function asUint64Array(Witnet.Result memory _result) external pure returns (uint64[] memory); } // File: node_modules\witnet-solidity-bridge\contracts\WitnetRequestBoard.sol /// @title Witnet Request Board functionality base contract. /// @author The Witnet Foundation. abstract contract WitnetRequestBoard is IWitnetRequestBoardEvents, IWitnetRequestBoardReporter, IWitnetRequestBoardRequestor, IWitnetRequestBoardView, IWitnetRequestParser { receive() external payable { revert("WitnetRequestBoard: no transfers accepted"); } } // File: witnet-solidity-bridge\contracts\UsingWitnet.sol /// @title The UsingWitnet contract /// @dev Witnet-aware contracts can inherit from this contract in order to interact with Witnet. /// @author The Witnet Foundation. abstract contract UsingWitnet { WitnetRequestBoard public immutable witnet; /// Include an address to specify the WitnetRequestBoard entry point address. /// @param _wrb The WitnetRequestBoard entry point address. constructor(WitnetRequestBoard _wrb) { require(address(_wrb) != address(0), "UsingWitnet: zero address"); witnet = _wrb; } /// Provides a convenient way for client contracts extending this to block the execution of the main logic of the /// contract until a particular request has been successfully solved and reported by Witnet. modifier witnetRequestSolved(uint256 _id) { require( _witnetCheckResultAvailability(_id), "UsingWitnet: request not solved" ); _; } /// Check if a data request has been solved and reported by Witnet. /// @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third. /// parties) before this method returns `true`. /// @param _id The unique identifier of a previously posted data request. /// @return A boolean telling if the request has been already resolved or not. Returns `false` also, if the result was deleted. function _witnetCheckResultAvailability(uint256 _id) internal view virtual returns (bool) { return witnet.getQueryStatus(_id) == Witnet.QueryStatus.Reported; } /// Estimate the reward amount. /// @param _gasPrice The gas price for which we want to retrieve the estimation. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward(uint256 _gasPrice) internal view virtual returns (uint256) { return witnet.estimateReward(_gasPrice); } /// Estimates the reward amount, considering current transaction gas price. /// @return The reward to be included when either posting a new request, or upgrading the reward of a previously posted one. function _witnetEstimateReward() internal view virtual returns (uint256) { return witnet.estimateReward(tx.gasprice); } /// Send a new request to the Witnet network with transaction value as a reward. /// @param _request An instance of `IWitnetRequest` contract. /// @return _id Sequential identifier for the request included in the WitnetRequestBoard. /// @return _reward Current reward amount escrowed by the WRB until a result gets reported. function _witnetPostRequest(IWitnetRequest _request) internal virtual returns (uint256 _id, uint256 _reward) { _reward = _witnetEstimateReward(); _id = witnet.postRequest{value: _reward}(_request); } /// Upgrade the reward for a previously posted request. /// @dev Call to `upgradeReward` function in the WitnetRequestBoard contract. /// @param _id The unique identifier of a request that has been previously sent to the WitnetRequestBoard. /// @return Amount in which the reward has been increased. function _witnetUpgradeReward(uint256 _id) internal virtual returns (uint256) { uint256 _currentReward = witnet.readRequestReward(_id); uint256 _newReward = _witnetEstimateReward(); uint256 _fundsToAdd = 0; if (_newReward > _currentReward) { _fundsToAdd = (_newReward - _currentReward); } witnet.upgradeReward{value: _fundsToAdd}(_id); // Let Request.gasPrice be updated return _fundsToAdd; } /// Read the Witnet-provided result to a previously posted request. /// @param _id The unique identifier of a request that was posted to Witnet. /// @return The result of the request as an instance of `Witnet.Result`. function _witnetReadResult(uint256 _id) internal view virtual returns (Witnet.Result memory) { return witnet.readResponseResult(_id); } /// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage. /// @param _id The unique identifier of a previously posted request. /// @return The Witnet-provided result to the request. function _witnetDeleteQuery(uint256 _id) internal virtual returns (Witnet.Response memory) { return witnet.deleteQuery(_id); } } // File: node_modules\witnet-solidity-bridge\contracts\requests\WitnetRequestBase.sol abstract contract WitnetRequestBase is IWitnetRequest { /// Contains a well-formed Witnet Data Request, encoded using Protocol Buffers. bytes public override bytecode; /// Returns SHA256 hash of Witnet Data Request as CBOR-encoded bytes. bytes32 public override hash; } // File: witnet-solidity-bridge\contracts\requests\WitnetRequest.sol contract WitnetRequest is WitnetRequestBase { using Witnet for bytes; constructor(bytes memory _bytecode) { bytecode = _bytecode; hash = _bytecode.hash(); } } // File: node_modules\@openzeppelin\contracts\utils\introspection\IERC165.sol /** * @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\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: node_modules\@openzeppelin\contracts\token\ERC721\IERC721Receiver.sol /** * @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\contracts\token\ERC721\extensions\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: node_modules\@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 * ==== */ 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: node_modules\@openzeppelin\contracts\utils\Context.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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: node_modules\@openzeppelin\contracts\utils\Strings.sol /** * @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: node_modules\@openzeppelin\contracts\utils\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\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, 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\access\Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin\contracts\security\ReentrancyGuard.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 ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin\contracts\utils\Counters.sol /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: contracts\libs\Witmons.sol /// @title Witmons Library: data model and helper functions /// @author Otherplane Labs, 2021. library Witmons { struct State { Parameters params; address decorator; IWitnetRequest witnetRNG; uint256 witnetQueryId; bytes32 witnetRandomness; uint256 hatchingBlock; Counters.Counter totalSupply; mapping (/* eggIndex => Creature */ uint256 => Creature) creatures; mapping (/* tokenId => eggIndex */ uint256 => uint256) eggIndex_; } struct Parameters { address signator; uint8[] percentileMarks; uint256 expirationBlocks; } enum Status { Batching, Randomizing, Hatching, Freezed } struct Creature { uint256 tokenId; uint256 eggBirth; uint256 eggIndex; uint256 eggScore; uint256 eggRanking; bytes32 eggPhenotype; CreatureCategory eggCategory; } enum CreatureCategory { Legendary, // 0 Rare, // 1 Common // 2 } enum CreatureStatus { Inexistent, // 0 Incubating, // 1 Hatching, // 2 Alive, // 3 Freezed // 4 } /// Calculate creature category. function creatureCategory(State storage _self, uint8 _percentile100) internal view returns (CreatureCategory) { uint8 _i; uint8 _cumuled; for (; _i < _self.params.percentileMarks.length; _i ++) { _cumuled += _self.params.percentileMarks[_i]; if (_percentile100 <= _cumuled) { break; } } return CreatureCategory(_i); } /// Gets tender's current status. function status(State storage self) internal view returns (Status) { if (self.witnetRandomness != bytes32(0)) { return (block.number > self.hatchingBlock + self.params.expirationBlocks) ? Status.Freezed : Status.Hatching; } else if (self.witnetQueryId > 0) { return Status.Randomizing; } else { return Status.Batching; } } /// @dev Produces revert message when tender is not in expected status. function statusRevertMessage(Status _status) internal pure returns (string memory) { if (_status == Status.Freezed) { return "Witmons: not in Freezed status"; } else if (_status == Status.Batching) { return "Witmons: not in Batching status"; } else if (_status == Status.Randomizing) { return "Witmons: not in Randomizing status"; } else if (_status == Status.Hatching) { return "Witmons: not in Hatching status"; } else { return "Witmons: bad mood"; } } /// Returns index of Most Significant Bit of given number, applying De Bruijn O(1) algorithm. function msbDeBruijn32(uint32 _v) internal pure returns (uint8) { uint8[32] memory _bitPosition = [ 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 ]; _v |= _v >> 1; _v |= _v >> 2; _v |= _v >> 4; _v |= _v >> 8; _v |= _v >> 16; return _bitPosition[ uint32(_v * uint256(0x07c4acdd)) >> 27 ]; } /// Generates pseudo-random number uniformly distributed in range [0 .. _range). function randomUint8(bytes32 _seed, uint256 _index, uint8 _range) internal pure returns (uint8) { assert(_range > 0); uint8 _flagBits = uint8(255 - msbDeBruijn32(uint32(_range))); uint256 _number = uint256(keccak256(abi.encode(_seed, _index))) & uint256(2 ** _flagBits - 1); return uint8((_number * _range) >> _flagBits); } /// Recovers address from hash and signature. function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } } // File: contracts\interfaces\IWitmonDecorator.sol /// @title Witty Creatures 2.0 Decorating interface. /// @author Otherplane Labs, 2021. interface IWitmonDecorator { function baseURI() external view returns (string memory); function getCreatureImage(Witmons.Creature memory) external view returns (string memory); function getCreatureMetadata(Witmons.Creature memory) external view returns (string memory); } // File: contracts\interfaces\IWitmonAdmin.sol /// @title Witty Creatures 2.0 Token only-owner interface. /// @author Otherplane Labs, 2021. interface IWitmonAdmin { /// Change token/creature decorator. /// @param _decorator Decorating logic contract producing a creature's metadata, and picture. function setDecorator(IWitmonDecorator _decorator) external; /// Change batch parameters. Only possible while in 'Batching' status. /// @param _signator Externally-owned account authorize to sign egg's info before minting. /// @param _percentileMarks Creature-category ordered percentile marks (Legendary first). /// @param _expirationBlocks Number of blocks after Witnet randomness is generated, /// during which creatures may be minted. function setParameters( address _signator, uint8[] calldata _percentileMarks, uint256 _expirationBlocks ) external; /// Stops batching, which means: (a) parameters cannot change anymore, and (b) a /// random number will requested to the Witnet Decentralized Oracle Network. /// @dev While request is being attended, tender will remain in 'Randomizing' status. function stopBatching() external payable; /// Starts hatching, which means that minting of creatures will start to be possible, /// until the hatching period expires (see `_hatchingExpirationBlocks`). /// @dev During the hatching period the tender will remain in 'Hatching status'. Once the /// @dev hatching period expires, tender status will automatically change to 'Freezed'. function startHatching() external; } // File: contracts\interfaces\IWitmonEvents.sol /// @title Witty Creatures 2.0 Token events. /// @author Otherplane Labs, 2021. interface IWitmonEvents { event BatchParameters( address signator, uint8[] percentileMarks, uint256 expirationBlocks ); event DecoratorSet(IWitmonDecorator decorator); event WitnetResult(bytes32 randomness); event WitnetError(string reason); event NewCreature(uint256 eggIndex, uint256 tokenId); } // File: contracts\interfaces\IWitmonSurrogates.sol /// @title Witty Creatures 2.0 Token surrogating interface. /// @author Otherplane Labs, 2021. interface IWitmonSurrogates { function mintCreature( address _eggOwner, uint256 _eggIndex, uint256 _eggScore, uint256 _eggRanking, uint256 _totalClaimedEggs, bytes calldata _signature ) external; function previewCreatureImage( address _eggOwner, uint256 _eggIndex, uint256 _eggScore, uint256 _eggRanking, uint256 _totalClaimedEggs, bytes calldata _signature ) external view returns (string memory); } // File: contracts\interfaces\IWitmonView.sol /// @title Witty Creatures 2.0 Token viewing interface. /// @author Otherplane Labs, 2021. interface IWitmonView { function getCreatureData(uint256 _eggIndex) external view returns (Witmons.Creature memory); function getCreatureImage(uint256 _eggIndex) external view returns (string memory); function getCreatureStatus(uint256 _eggIndex) external view returns (Witmons.CreatureStatus); function getDecorator() external view returns (IWitmonDecorator); function getParameters() external view returns (Witmons.Parameters memory); function getTokenEggIndex(uint256 _tokenId) external view returns (uint256); function totalSupply() external view returns (uint256 _totalSupply); function getStatus() external view returns (Witmons.Status); } // File: contracts\WitmonERC721.sol /// @title Witty Creatures 2.0 - ERC721 Token contract /// @author Otherplane Labs, 2021. contract WitmonERC721 is ERC721, Ownable, ReentrancyGuard, UsingWitnet, IWitmonAdmin, IWitmonEvents, IWitmonSurrogates, IWitmonView { using Counters for Counters.Counter; using Strings for bytes32; using Strings for uint256; using Witmons for Witmons.State; Witmons.State internal _state; modifier inStatus(Witmons.Status _status) { require( _state.status() == _status, Witmons.statusRevertMessage(_status) ); _; } modifier tokenExists(uint256 _tokenId) { require( _exists(_tokenId), "WitmonERC721: inexistent token" ); _; } constructor( WitnetRequestBoard _witnet, IWitmonDecorator _decorator, string memory _name, string memory _symbol, address _signator, uint8[] memory _percentileMarks, uint256 _expirationBlocks ) UsingWitnet(_witnet) ERC721(_name, _symbol) { setDecorator(_decorator); setParameters( _signator, _percentileMarks, _expirationBlocks ); _state.witnetRNG = new WitnetRequest(hex"0a0f120508021a01801a0210022202100b10e807180a200a2833308094ebdc03"); } // ======================================================================== // --- 'ERC721Metadata' overriden functions ------------------------------- function baseURI() public view virtual returns (string memory) { return IWitmonDecorator(_state.decorator).baseURI(); } function metadata(uint256 _tokenId) external virtual view tokenExists(_tokenId) returns (string memory) { uint256 _eggIndex = _state.eggIndex_[_tokenId]; Witmons.Creature memory _creature = _state.creatures[_eggIndex]; assert(_tokenId == _creature.tokenId); return IWitmonDecorator(_state.decorator).getCreatureMetadata(_creature); } function tokenURI(uint256 _tokenId) public view virtual override tokenExists(_tokenId) returns (string memory) { return string(abi.encodePacked( baseURI(), _tokenId.toString() )); } // ======================================================================== // --- Implementation of 'IWitmonAdmin' ----------------------------------- /// Change token/creature decorator. /// @param _decorator Decorating logic contract producing a creature's metadata, and picture. function setDecorator(IWitmonDecorator _decorator) public virtual override onlyOwner // inState(Witmons.Status.Batching) { require(address(_decorator) != address(0), "WitmonERC721: no decorator"); _state.decorator = address(_decorator); emit DecoratorSet(_decorator); } /// Change batch parameters. Only possible while in 'Batching' status. /// @param _signator Externally-owned account authorize to sign egg's info before minting. /// @param _percentileMarks Creature-category ordered percentile marks (Legendary first). /// @param _expirationBlocks Number of blocks after Witnet randomness is generated, /// during which creatures may be minted. function setParameters( address _signator, uint8[] memory _percentileMarks, uint256 _expirationBlocks ) public virtual override onlyOwner inStatus(Witmons.Status.Batching) { require(_signator != address(0), "WitmonERC721: no signator"); require(_percentileMarks.length == uint8(Witmons.CreatureCategory.Common) + 1, "WitmonERC721: bad percentile marks"); _state.params.percentileMarks = new uint8[](_percentileMarks.length); uint8 _checkSum; for (uint8 _i = 0; _i < _percentileMarks.length; _i ++) { uint8 _mark = _percentileMarks[_i]; _state.params.percentileMarks[_i] = _mark; _checkSum += _mark; } require(_checkSum == 100, "WitmonERC721: bad percentile checksum"); _state.params.signator = _signator; _state.params.expirationBlocks = _expirationBlocks; emit BatchParameters( _signator, _percentileMarks, _expirationBlocks ); } /// Stops batching, which means: (a) parameters cannot change anymore, and (b) a /// random number will requested to the Witnet Decentralized Oracle Network. /// @dev While request is being attended, tender will remain in 'Randomizing' status. function stopBatching() external payable virtual override nonReentrant onlyOwner inStatus(Witmons.Status.Batching) { // Send the request to Witnet and store the ID for later retrieval of the result: uint256 _witnetReward; (_state.witnetQueryId, _witnetReward) = _witnetPostRequest(_state.witnetRNG); // Transfers back unused funds: if (msg.value > _witnetReward) { payable(msg.sender).transfer(msg.value - _witnetReward); } } /// Starts hatching, which means that minting of creatures will start to be possible, /// until the hatching period expires (see `_state.expirationBlocks`). /// @dev During the hatching period the tender will remain in 'Hatching status'. Once the /// @dev hatching period expires, tender status will automatically change to 'Freezed'. function startHatching() external virtual override onlyOwner inStatus(Witmons.Status.Randomizing) { uint _queryId = _state.witnetQueryId; require( _witnetCheckResultAvailability(_queryId), "WitmonERC721: randomness not yet solved" ); Witnet.Result memory _result = witnet.readResponseResult(_queryId); if (_result.success) { bytes32 _randomness = _bytesToBytes32(witnet.asBytes(_result)); _state.hatchingBlock = block.number; _state.witnetRandomness = _randomness; emit WitnetResult(_randomness); } else { _state.witnetQueryId = 0; string memory _errorMessage; // Try to read the value as an error message, catch error bytes if read fails try witnet.asErrorMessage(_result) returns (Witnet.ErrorCodes, string memory e) { _errorMessage = e; } catch (bytes memory _errorBytes) { _errorMessage = string(_errorBytes); } emit WitnetError(_errorMessage); } } // ======================================================================== // --- Implementation of 'IWitmonSurrogates' ------------------------------- function mintCreature( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes calldata _signature ) external virtual override nonReentrant inStatus(Witmons.Status.Hatching) { _verifySignatorSignature( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Verify not already minted: require( _state.creatures[_eggIndex].tokenId == 0, "WitmonERC721: already minted" ); // Increment token supply: _state.totalSupply.increment(); uint256 _tokenId = _state.totalSupply.current(); // Fulfill creature data: Witmons.Creature memory _creature = _mintCreature( _tokenId, block.timestamp, // solhint-disable not-rely-on-time _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Write to storage: _state.creatures[_eggIndex] = _creature; _state.eggIndex_[_tokenId] = _eggIndex; // Mint the token: _safeMint(_eggOwner, _tokenId); emit NewCreature(_eggIndex, _tokenId); } function previewCreatureImage( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes calldata _signature ) external view virtual override inStatus(Witmons.Status.Hatching) returns (string memory) { _verifySignatorSignature( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ); // Preview creature image: return IWitmonDecorator(_state.decorator).getCreatureImage( _mintCreature( 0, 0, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs, _signature ) ); } // ======================================================================== // --- Implementation of 'IWitmonView' ------------------------------------ function getCreatureData(uint256 _eggIndex) public view override returns (Witmons.Creature memory) { return _state.creatures[_eggIndex]; } function getCreatureImage(uint256 _eggIndex) public view override returns (string memory) { require( getCreatureStatus(_eggIndex) == Witmons.CreatureStatus.Alive, "WitmonERC721: not alive yet" ); Witmons.Creature memory _creature = _state.creatures[_eggIndex]; return IWitmonDecorator(_state.decorator).getCreatureImage(_creature); } function getCreatureStatus(uint256 _eggIndex) public view virtual override returns (Witmons.CreatureStatus) { Witmons.Creature storage _creature = _state.creatures[_eggIndex]; if (_creature.eggPhenotype != bytes32(0)) { return Witmons.CreatureStatus.Alive; } else { Witmons.Status _tenderStatus = _state.status(); if (_tenderStatus == Witmons.Status.Hatching) { return Witmons.CreatureStatus.Hatching; } else if (_tenderStatus == Witmons.Status.Freezed) { return Witmons.CreatureStatus.Freezed; } else { return Witmons.CreatureStatus.Incubating; } } } function getDecorator() external view override returns (IWitmonDecorator) { return IWitmonDecorator(_state.decorator); } function getParameters() external view override returns (Witmons.Parameters memory) { return _state.params; } function getTokenEggIndex(uint256 _tokenId) external view override returns (uint256) { return _state.eggIndex_[_tokenId]; } function totalSupply() public view override returns ( uint256 _totalSupply ) { return ( _state.totalSupply.current() ); } function getStatus() public view override returns (Witmons.Status) { return _state.status(); } // ------------------------------------------------------------------------ // --- INTERNAL VIRTUAL METHODS ------------------------------------------- // ------------------------------------------------------------------------ function _mintCreature( uint256 _tokenId, uint256 _tokenInception, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes memory _signature ) internal view virtual returns (Witmons.Creature memory) { uint8 _percentile100 = _eggRanking > _totalClaimedEggs ? 100 : uint8((_eggRanking * 100) / _totalClaimedEggs) ; return Witmons.Creature({ tokenId: _tokenId, eggBirth: _tokenInception, eggCategory: _state.creatureCategory(_percentile100), eggIndex: _eggIndex, eggScore: _eggScore, eggRanking: _eggRanking, eggPhenotype: keccak256(abi.encodePacked( _signature, _state.witnetRandomness )) }); } function _verifySignatorSignature( address _eggOwner, uint256 _eggIndex, uint256 _eggRanking, uint256 _eggScore, uint256 _totalClaimedEggs, bytes memory _signature ) internal view virtual { // Verify signator: bytes32 _eggHash = keccak256(abi.encodePacked( _eggOwner, _eggIndex, _eggRanking, _eggScore, _totalClaimedEggs )); require( Witmons.recoverAddr(_eggHash, _signature) == _state.params.signator, "WitmonERC721: bad signature" ); } // ------------------------------------------------------------------------ // --- PRIVATE METHODS ---------------------------------------------------- // ------------------------------------------------------------------------ function _bytesToBytes32(bytes memory _bb) private pure returns (bytes32 _r) { uint _len = _bb.length > 32 ? 32 : _bb.length; for (uint _i = 0; _i < _len; _i ++) { _r |= bytes32(_bb[_i] & 0xff) >> (_i * 8); } } }
File: contracts\libs\Witmons.sol @title Witmons Library: data model and helper functions @author Otherplane Labs, 2021.
library Witmons { struct State { Parameters params; address decorator; IWitnetRequest witnetRNG; uint256 witnetQueryId; bytes32 witnetRandomness; uint256 hatchingBlock; Counters.Counter totalSupply; mapping (/* eggIndex => Creature */ uint256 => Creature) creatures; mapping (/* tokenId => eggIndex */ uint256 => uint256) eggIndex_; } struct Parameters { address signator; uint8[] percentileMarks; uint256 expirationBlocks; } enum Status { Batching, Randomizing, Hatching, Freezed } struct Creature { uint256 tokenId; uint256 eggBirth; uint256 eggIndex; uint256 eggScore; uint256 eggRanking; bytes32 eggPhenotype; CreatureCategory eggCategory; } enum CreatureCategory { } enum CreatureStatus { } function creatureCategory(State storage _self, uint8 _percentile100) internal view returns (CreatureCategory) { uint8 _i; uint8 _cumuled; for (; _i < _self.params.percentileMarks.length; _i ++) { _cumuled += _self.params.percentileMarks[_i]; if (_percentile100 <= _cumuled) { break; } } return CreatureCategory(_i); } function creatureCategory(State storage _self, uint8 _percentile100) internal view returns (CreatureCategory) { uint8 _i; uint8 _cumuled; for (; _i < _self.params.percentileMarks.length; _i ++) { _cumuled += _self.params.percentileMarks[_i]; if (_percentile100 <= _cumuled) { break; } } return CreatureCategory(_i); } function creatureCategory(State storage _self, uint8 _percentile100) internal view returns (CreatureCategory) { uint8 _i; uint8 _cumuled; for (; _i < _self.params.percentileMarks.length; _i ++) { _cumuled += _self.params.percentileMarks[_i]; if (_percentile100 <= _cumuled) { break; } } return CreatureCategory(_i); } function status(State storage self) internal view returns (Status) { if (self.witnetRandomness != bytes32(0)) { return (block.number > self.hatchingBlock + self.params.expirationBlocks) ? Status.Freezed : Status.Hatching; return Status.Randomizing; return Status.Batching; } } function status(State storage self) internal view returns (Status) { if (self.witnetRandomness != bytes32(0)) { return (block.number > self.hatchingBlock + self.params.expirationBlocks) ? Status.Freezed : Status.Hatching; return Status.Randomizing; return Status.Batching; } } } else if (self.witnetQueryId > 0) { } else { function statusRevertMessage(Status _status) internal pure returns (string memory) { if (_status == Status.Freezed) { return "Witmons: not in Freezed status"; return "Witmons: not in Batching status"; return "Witmons: not in Randomizing status"; return "Witmons: not in Hatching status"; return "Witmons: bad mood"; } } function statusRevertMessage(Status _status) internal pure returns (string memory) { if (_status == Status.Freezed) { return "Witmons: not in Freezed status"; return "Witmons: not in Batching status"; return "Witmons: not in Randomizing status"; return "Witmons: not in Hatching status"; return "Witmons: bad mood"; } } } else if (_status == Status.Batching) { } else if (_status == Status.Randomizing) { } else if (_status == Status.Hatching) { } else { function msbDeBruijn32(uint32 _v) internal pure returns (uint8) { uint8[32] memory _bitPosition = [ 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 ]; _v |= _v >> 1; _v |= _v >> 2; _v |= _v >> 4; _v |= _v >> 8; _v |= _v >> 16; return _bitPosition[ uint32(_v * uint256(0x07c4acdd)) >> 27 ]; } function randomUint8(bytes32 _seed, uint256 _index, uint8 _range) internal pure returns (uint8) { assert(_range > 0); uint8 _flagBits = uint8(255 - msbDeBruijn32(uint32(_range))); uint256 _number = uint256(keccak256(abi.encode(_seed, _index))) & uint256(2 ** _flagBits - 1); return uint8((_number * _range) >> _flagBits); } function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); } }
6,983,706
[ 1, 812, 30, 20092, 64, 21571, 64, 59, 305, 2586, 87, 18, 18281, 225, 678, 305, 2586, 87, 18694, 30, 501, 938, 471, 4222, 4186, 225, 4673, 21314, 511, 5113, 16, 26599, 21, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 678, 305, 2586, 87, 288, 203, 203, 565, 1958, 3287, 288, 203, 3639, 7012, 859, 31, 203, 3639, 1758, 7367, 31, 203, 3639, 467, 59, 305, 2758, 691, 31039, 2758, 54, 4960, 31, 203, 3639, 2254, 5034, 31039, 2758, 1138, 548, 31, 203, 3639, 1731, 1578, 31039, 2758, 8529, 4496, 31, 203, 3639, 2254, 5034, 366, 505, 310, 1768, 31, 540, 203, 3639, 9354, 87, 18, 4789, 2078, 3088, 1283, 31, 203, 3639, 2874, 261, 20308, 25144, 1016, 516, 5799, 1231, 1195, 2254, 5034, 516, 5799, 1231, 13, 1519, 2790, 31, 203, 3639, 2874, 261, 20308, 1147, 548, 225, 516, 25144, 1016, 1195, 2254, 5034, 516, 2254, 5034, 13, 25144, 1016, 67, 31, 203, 565, 289, 203, 203, 565, 1958, 7012, 288, 203, 3639, 1758, 1573, 639, 31, 203, 3639, 2254, 28, 8526, 17279, 20981, 31, 4202, 203, 3639, 2254, 5034, 7686, 6450, 31, 203, 565, 289, 203, 203, 565, 2792, 2685, 288, 203, 3639, 5982, 310, 16, 203, 3639, 8072, 6894, 16, 203, 3639, 670, 505, 310, 16, 203, 3639, 15217, 94, 329, 203, 565, 289, 203, 203, 565, 1958, 5799, 1231, 288, 203, 3639, 2254, 5034, 1147, 548, 31, 27699, 3639, 2254, 5034, 25144, 25791, 31, 203, 3639, 2254, 5034, 25144, 1016, 31, 203, 3639, 2254, 5034, 25144, 7295, 31, 203, 3639, 2254, 5034, 25144, 12925, 310, 31, 203, 3639, 1731, 1578, 25144, 3731, 275, 10570, 31, 203, 3639, 5799, 1231, 4457, 25144, 4457, 31, 203, 565, 289, 203, 203, 565, 2792, 5799, 1231, 4457, 288, 203, 565, 289, 203, 203, 2 ]
pragma solidity ^0.4.24; /** * @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); } /** * @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; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * 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; } } /** * @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(); } } /** * @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); } } /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract GemstoneChain is PausableToken, DetailedERC20 { constructor() DetailedERC20("Gemstone Chain", "GESC", 18) public { totalSupply_ = 2000000000 * 10 ** 18; balances[msg.sender] = totalSupply(); } }
* @title DetailedERC20 token @dev The decimals are only for visualization purposes. All the operations are done using the smallest and indivisible token unit, just as on Ethereum all the operations are done in wei./
contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } }
14,761,187
[ 1, 40, 6372, 654, 39, 3462, 1147, 225, 1021, 15105, 854, 1338, 364, 30056, 13694, 18, 4826, 326, 5295, 854, 2731, 1450, 326, 13541, 471, 6335, 18932, 1147, 2836, 16, 2537, 487, 603, 512, 18664, 379, 777, 326, 5295, 854, 2731, 316, 732, 77, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 6372, 654, 39, 3462, 353, 4232, 39, 3462, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 203, 565, 3885, 12, 1080, 389, 529, 16, 533, 389, 7175, 16, 2254, 28, 389, 31734, 13, 1071, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 3639, 3273, 273, 389, 7175, 31, 203, 3639, 15105, 273, 389, 31734, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Created on 2018-06-05 16:37 * @summary: Our NFT Minting Contract which inherits ERC721 capability from LSNFT * @author: Fazri Zubair & Farhan Khwaja */ pragma solidity ^0.4.23; pragma solidity ^0.4.23; /* NFT Metadata Schema { "title": "Asset Metadata", "type": "object", "properties": { "name": { "type": "string", "description": "Identifies the asset to which this NFT represents", }, "description": { "type": "string", "description": "Describes the asset to which this NFT represents", }, "image": { "type": "string", "description": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive.", } } } */ /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } } /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 public constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require (ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require (isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require (_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require (owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require (_to != owner); require (msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require (_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require (checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require (_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require (tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require (ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev 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 whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 public constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received( address, address, uint256, bytes ) public returns(bytes4) { return ERC721_RECEIVED; } } /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Base Server Address for Token MetaData URI string internal tokenURIBase; /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require (exists(_tokenId)); return tokenURIBase; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require (_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require (_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _uri string URI to assign */ function _setTokenURIBase(string _uri) internal { tokenURIBase = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; // This also deletes the contents at the last position of the array ownedTokens[_from].length--; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7; /* bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Enumerable = 0x780e9d63; /* bytes4(keccak256(&#39;totalSupply()&#39;)) ^ bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721Metadata = 0x5b5e139f; /* bytes4(keccak256(&#39;name()&#39;)) ^ bytes4(keccak256(&#39;symbol()&#39;)) ^ bytes4(keccak256(&#39;tokenURI(uint256)&#39;)); */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /* bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)); */ bytes4 public constant InterfaceSignature_ERC721Optional =- 0x4f558e79; /* bytes4(keccak256(&#39;exists(uint256)&#39;)); */ /** * @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). * @dev Returns true for any standardized interfaces implemented by this contract. * @param _interfaceID bytes4 the interface to check for * @return true for any standardized interfaces implemented by this contract. */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721) || (_interfaceID == InterfaceSignature_ERC721Enumerable) || (_interfaceID == InterfaceSignature_ERC721Metadata)); } function implementsERC721() public pure returns (bool) { return true; } } /* Lucid Sight, Inc. ERC-721 Collectibles. * @title LSNFT - Lucid Sight, Inc. Non-Fungible Token * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract LSNFT is ERC721Token { /*** EVENTS ***/ /// @dev The Created event is fired whenever a new collectible comes into existence. event Created(address owner, uint256 tokenId); /*** DATATYPES ***/ struct NFT { // The sequence of potential attributes a Collectible has and can provide in creation events. Used in Creation logic to spwan new Cryptos uint256 attributes; // Current Game Card identifier uint256 currentGameCardId; // MLB Game Identifier (if asset generated as a game reward) uint256 mlbGameId; // player orverride identifier uint256 playerOverrideId; // official MLB Player ID uint256 mlbPlayerId; // earnedBy : In some instances we may want to retroactively write which MLB player triggered // the event that created a Legendary Trophy. This optional field should be able to be written // to after generation if we determine an event was newsworthy enough uint256 earnedBy; // asset metadata uint256 assetDetails; // Attach/Detach Flag uint256 isAttached; } NFT[] allNFTs; function isLSNFT() public view returns (bool) { return true; } /// For creating NFT function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); // Created event emit Created(_owner, newLSNFTId); return newLSNFTId; } /// @dev Gets attributes of NFT function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) { NFT storage lsnftObj = allNFTs[_tokenId]; return lsnftObj; } function _approveForSale(address _owner, address _to, uint256 _tokenId) internal { address owner = ownerOf(_tokenId); require (_to != owner); require (_owner == owner || isApprovedForAll(owner, _owner)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(_owner, _to, _tokenId); } } } /** Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { /// Facilitates access & control for the game. /// Roles: /// -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) /// -The Banker: The Bank can withdraw funds and adjust fees / prices. /// -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); /// @dev The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /** * @dev Operation modifiers for limiting access only to Managers */ modifier onlyManager() { require (msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Operation modifiers for limiting access to only Banker */ modifier onlyBanker() { require (msg.sender == bankManager); _; } /** * @dev Operation modifiers for any Operators */ modifier anyOperator() { require ( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /** * @dev Operation modifier for any Other Manager */ modifier onlyOtherManagers() { require (otherManagers[msg.sender] == 1); _; } /** * @dev Assigns a new address to act as the Primary Manager. * @param _newGM New primary manager address */ function setPrimaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerPrimary = _newGM; } /** * @dev Assigns a new address to act as the Secondary Manager. * @param _newGM New Secondary Manager Address */ function setSecondaryManager(address _newGM) external onlyManager { require (_newGM != address(0)); managerSecondary = _newGM; } /** * @dev Assigns a new address to act as the Banker. * @param _newBK New Banker Address */ function setBanker(address _newBK) external onlyManager { require (_newBK != address(0)); bankManager = _newBK; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require (_newOp != address(0)); otherManagers[_newOp] = _state; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require (!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require (paused); _; } /// @dev Modifier to allow actions only when the contract has Error modifier whenError { require (error); _; } /** * @dev Called by any Operator role to pause the contract. * Used only if a bug or exploit is discovered (Here to limit losses / damage) */ function pause() external onlyManager whenNotPaused { paused = true; } /** * @dev Unpauses the smart contract. Can only be called by the Game Master */ function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /** * @dev Errors out the contract thus mkaing the contract non-functionable */ function hasError() public onlyManager whenPaused { error = true; } /** * @dev Removes the Error Hold from the contract and resumes it for working */ function noError() public onlyManager whenPaused { error = false; } } /** Base contract for DodgersNFT Collectibles. Holds all commons, events and base variables. * @title Lucid Sight MLB NFT 2018 * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CollectibleBase is LSNFT { /*** EVENTS ***/ /// @dev Event emitted when an attribute of the player is updated event AssetUpdated(uint256 tokenId); /*** STORAGE ***/ /// @dev A mapping of Team Id to Team Sequence Number to Collectible mapping (uint256 => mapping (uint32 => uint256) ) public nftTeamIdToSequenceIdToCollectible; /// @dev A mapping from Team IDs to the Sequqence Number . mapping (uint256 => uint32) public nftTeamIndexToCollectibleCount; /// @dev Array to hold details on attachment for each LS NFT Collectible mapping(uint256 => uint256[]) public nftCollectibleAttachments; /// @dev Mapping to control the asset generation per season. mapping(uint256 => uint256) public generationSeasonController; /// @dev Mapping for generation Season Dict. mapping(uint256 => uint256) public generationSeasonDict; /// @dev internal function to update player override id function _updatePlayerOverrideId(uint256 _tokenId, uint256 _newPlayerOverrideId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.playerOverrideId = _newPlayerOverrideId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /** * @dev An internal method that helps in generation of new NFT Collectibles * @param _teamId teamId of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _isAttached State of the asset (attached or dettached) * @param _nftData Array of data required for creation */ function _createNFTCollectible( uint8 _teamId, uint256 _attributes, address _owner, uint256 _isAttached, uint256[5] _nftData ) internal returns (uint256) { uint256 generationSeason = (_attributes % 1000000).div(1000); require (generationSeasonController[generationSeason] == 1); uint32 _sequenceId = getSequenceId(_teamId); uint256 newNFTCryptoId = _createNFT(_nftData, _owner, _isAttached); nftTeamIdToSequenceIdToCollectible[_teamId][_sequenceId] = newNFTCryptoId; nftTeamIndexToCollectibleCount[_teamId] = _sequenceId; return newNFTCryptoId; } function getSequenceId(uint256 _teamId) internal returns (uint32) { return (nftTeamIndexToCollectibleCount[_teamId] + 1); } /** * @dev Internal function, Helps in updating the Creation Stop Time * @param _season Season UINT Code * @param _value 0 - Not allowed, 1 - Allowed */ function _updateGenerationSeasonFlag(uint256 _season, uint8 _value) internal { generationSeasonController[_season] = _value; } /** @param _owner The owner whose ships tokens we are interested in. * @dev This method MUST NEVER be called by smart contract code. First, it&#39;s fairly * expensive (it walks the entire Collectibles owners array looking for NFT belonging to owner) */ function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalItems = balanceOf(_owner); uint256 resultIndex = 0; // We count on the fact that all Collectible have IDs starting at 0 and increasing // sequentially up to the total count. uint256 _assetId; for (_assetId = 0; _assetId < totalItems; _assetId++) { result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId); resultIndex++; } return result; } } /// @dev internal function to update MLB player id function _updateMLBPlayerId(uint256 _tokenId, uint256 _newMLBPlayerId) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.mlbPlayerId = _newMLBPlayerId; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } /// @dev internal function to update asset earnedBy value for an asset/token function _updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) internal { // Get Token Obj NFT storage lsnftObj = allNFTs[_tokenId]; lsnftObj.earnedBy = _earnedBy; // Update Token Data with new updated attributes allNFTs[_tokenId] = lsnftObj; emit AssetUpdated(_tokenId); } } /* Handles creating new Collectibles for promo and seed. * @title CollectibleMinting Minting * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from KittyCore.sol created by Axiom Zen * Ref: ETH Contract - 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d */ contract CollectibleMinting is CollectibleBase, OperationalControl { uint256 public rewardsRedeemed = 0; /// @dev Counts the number of promo collectibles that can be made per-team uint256[31] public promoCreatedCount; /// @dev Counts the number of seed collectibles that can be made in total uint256 public seedCreatedCount; /// @dev Bool to toggle batch support bool public isBatchSupported = true; /// @dev A mapping of contracts that can trigger functions mapping (address => bool) public contractsApprovedList; /** * @dev Helps to toggle batch supported flag * @param _flag The flag */ function updateBatchSupport(bool _flag) public onlyManager { isBatchSupported = _flag; } modifier canCreate() { require (contractsApprovedList[msg.sender] || msg.sender == managerPrimary || msg.sender == managerSecondary); _; } /** * @dev Add an address to the Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function addToApproveList(address _newAddress) public onlyManager { require (!contractsApprovedList[_newAddress]); contractsApprovedList[_newAddress] = true; } /** * @dev Remove an address from Approved List * @param _newAddress The new address to be approved for interaction with the contract */ function removeFromApproveList(address _newAddress) public onlyManager { require (contractsApprovedList[_newAddress]); delete contractsApprovedList[_newAddress]; } /** * @dev Generates promo collectibles. Only callable by Game Master, with isAttached as 0. * @notice The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createPromoCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } if(allNFTs.length > 0) { promoCreatedCount[_teamId]++; } uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generaes a new single seed Collectible, with isAttached as 0. * @notice Helps in creating seed collectible.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createSeedCollectible( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } seedCreatedCount++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new Reward Collectible and transfer it to the owner, with isAttached as 0. * @notice Helps in redeeming the Rewards using our Oracle. Creates & transfers the asset to the redeemer (_owner) * The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner (redeemer) of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createRewardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 0, _nftData); } /** * @dev Generate new ETH Card Collectible, with isAttached as 2. * @notice Helps to generate Collectibles/Tokens/Asset and transfer to ETH Cards, * which can be redeemed using our web-app.The generation of an asset if limited via the generationSeasonController * @param _teamId teamId of the asset/token/collectible * @param _posId position of the asset/token/collectible * @param _attributes attributes of asset/token/collectible * @param _owner owner of asset/token/collectible * @param _gameId mlb game Identifier * @param _playerOverrideId player override identifier * @param _mlbPlayerId official mlb player identifier */ function createETHCardCollectible ( uint8 _teamId, uint8 _posId, uint256 _attributes, address _owner, uint256 _gameId, uint256 _playerOverrideId, uint256 _mlbPlayerId) external canCreate whenNotPaused returns (uint256) { address nftOwner = _owner; if (nftOwner == address(0)) { nftOwner = managerPrimary; } rewardsRedeemed++; uint32 _sequenceId = getSequenceId(_teamId); uint256 assetDetails = uint256(uint64(now)); assetDetails |= uint256(_sequenceId)<<64; assetDetails |= uint256(_teamId)<<96; assetDetails |= uint256(_posId)<<104; uint256[5] memory _nftData = [assetDetails, _attributes, _gameId, _playerOverrideId, _mlbPlayerId]; return _createNFTCollectible(_teamId, _attributes, nftOwner, 2, _nftData); } } /* @title Interface for DodgersNFT Contract * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract SaleManager { function createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _owner) external; } /** * DodgersNFT manages all aspects of the Lucid Sight, Inc. CryptoBaseball. * @title DodgersNFT * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract DodgersNFT is CollectibleMinting { /// @dev Set in case the DodgersNFT contract requires an upgrade address public newContractAddress; string public constant MLB_Legal = "Major League Baseball trademarks and copyrights are used with permission of the applicable MLB entity. All rights reserved."; // Time LS Oracle has to respond to detach requests uint32 public detachmentTime = 0; // Indicates if attached system is Active (Transfers will be blocked if attached and active) bool public attachedSystemActive; // Sale Manager Contract SaleManager public saleManagerAddress; /** * @dev DodgersNFT constructor. */ constructor() public { // Starts paused. paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; name_ = "LucidSight-DODGERS-NFT"; symbol_ = "DNFTCB"; } /** * @dev Sets the address for the NFT Contract * @param _saleManagerAddress The nft address */ function setSaleManagerAddress(address _saleManagerAddress) public onlyManager { require (_saleManagerAddress != address(0)); saleManagerAddress = SaleManager(_saleManagerAddress); } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { uint256 isAttached = checkIsAttached(_tokenId); if(isAttached == 2) { //One-Time Auth for Physical Card Transfers require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); updateIsAttached(_tokenId, 0); } else if(attachedSystemActive == true && isAttached >= 1) { require (msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); } else { require (isApprovedOrOwner(msg.sender, _tokenId)); } _; } /** * @dev Used to mark the smart contract as upgraded, in case of a issue * @param _v2Address The new contract address */ function setNewAddress(address _v2Address) external onlyManager { require (_v2Address != address(0)); newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /** * @dev Returns all the relevant information about a specific Collectible. * @notice Get details about your collectible * @param _tokenId The token identifier * @return isAttached Is Object attached * @return teamId team identifier of the asset/token/collectible * @return positionId position identifier of the asset/token/collectible * @return creationTime creation timestamp * @return attributes attribute of the asset/token/collectible * @return currentGameCardId current game card of the asset/token/collectible * @return mlbGameID mlb game identifier in which the asset/token/collectible was generated * @return playerOverrideId player override identifier of the asset/token/collectible * @return playerStatus status of the player (Rookie/Veteran/Historical) * @return playerHandedness handedness of the asset * @return mlbPlayerId official MLB Player Identifier */ function getCollectibleDetails(uint256 _tokenId) external view returns ( uint256 isAttached, uint32 sequenceId, uint8 teamId, uint8 positionId, uint64 creationTime, uint256 attributes, uint256 playerOverrideId, uint256 mlbGameId, uint256 currentGameCardId, uint256 mlbPlayerId, uint256 earnedBy, uint256 generationSeason ) { NFT memory obj = _getAttributesOfToken(_tokenId); attributes = obj.attributes; currentGameCardId = obj.currentGameCardId; mlbGameId = obj.mlbGameId; playerOverrideId = obj.playerOverrideId; mlbPlayerId = obj.mlbPlayerId; creationTime = uint64(obj.assetDetails); sequenceId = uint32(obj.assetDetails>>64); teamId = uint8(obj.assetDetails>>96); positionId = uint8(obj.assetDetails>>104); isAttached = obj.isAttached; earnedBy = obj.earnedBy; generationSeason = generationSeasonDict[(obj.attributes % 1000000) / 1000]; } /** * @dev This is public rather than external so we can call super.unpause * without using an expensive CALL. */ function unpause() public onlyManager { /// Actually unpause the contract. super.unpause(); } /** * @dev Helper function to get the teamID of a collectible.To avoid using getCollectibleDetails * @notice Returns the teamID associated with the asset/collectible/token * @param _tokenId The token identifier */ function getTeamId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 teamId = uint256(uint8(obj.assetDetails>>96)); return uint256(teamId); } /** * @dev Helper function to get the position of a collectible.To avoid using getCollectibleDetails * @notice Returns the position of the asset/collectible/token * @param _tokenId The token identifier */ function getPositionId(uint256 _tokenId) external view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 positionId = uint256(uint8(obj.assetDetails>>104)); return positionId; } /** * @dev Helper function to get the game card. To avoid using getCollectibleDetails * @notice Returns the gameCard associated with the asset/collectible/token * @param _tokenId The token identifier */ function getGameCardId(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.currentGameCardId; } /** * @dev Returns isAttached property value for an asset/collectible/token * @param _tokenId The token identifier */ function checkIsAttached(uint256 _tokenId) public view returns (uint256) { NFT memory obj = _getAttributesOfToken(_tokenId); return obj.isAttached; } /** * @dev Helper function to get the attirbute of the collectible.To avoid using getCollectibleDetails * @notice Returns the ability of an asset/collectible/token from attributes. * @param _tokenId The token identifier * @return ability ability of the asset */ function getAbilitiesForCollectibleId(uint256 _tokenId) external view returns (uint256 ability) { NFT memory obj = _getAttributesOfToken(_tokenId); uint256 _attributes = uint256(obj.attributes); ability = (_attributes % 1000); } /** * @dev Only allows trasnctions to go throught if the msg.sender is in the apporved list * @notice Updates the gameCardID properrty of the asset * @param _gameCardNumber The game card number * @param _playerId The player identifier */ function updateCurrentGameCardId(uint256 _gameCardNumber, uint256 _playerId) public whenNotPaused { require (contractsApprovedList[msg.sender]); NFT memory obj = _getAttributesOfToken(_playerId); obj.currentGameCardId = _gameCardNumber; if ( _gameCardNumber == 0 ) { obj.isAttached = 0; } else { obj.isAttached = 1; } allNFTs[_playerId] = obj; } /** * @dev Only Manager can add an attachment (special events) to the collectible * @notice Adds an attachment to collectible. * @param _tokenId The token identifier * @param _attachment The attachment */ function addAttachmentToCollectible ( uint256 _tokenId, uint256 _attachment) external onlyManager whenNotPaused { require (exists(_tokenId)); nftCollectibleAttachments[_tokenId].push(_attachment); emit AssetUpdated(_tokenId); } /** * @dev It will remove the attachment form the collectible. We will need to re-add all attachment(s) if removed. * @notice Removes all attachments from collectible. * @param _tokenId The token identifier */ function removeAllAttachmentsFromCollectible(uint256 _tokenId) external onlyManager whenNotPaused { require (exists(_tokenId)); delete nftCollectibleAttachments[_tokenId]; emit AssetUpdated(_tokenId); } /** * @notice Transfers the ownership of NFT from one address to another address * @dev responsible for gifting assets to other user. * @param _to to address * @param _tokenId The token identifier */ function giftAsset(address _to, uint256 _tokenId) public whenNotPaused { safeTransferFrom(msg.sender, _to, _tokenId); } /** * @dev responsible for setting the tokenURI. * @notice The user/developper needs to add the tokenID, in the end of URL, to * use the URI and get all details. Ex. www.<apiURL>.com/token/<tokenID> * @param _tokenURI The token uri */ function setTokenURIBase (string _tokenURI) public anyOperator { _setTokenURIBase(_tokenURI); } /** * @dev Allowed to be called by onlyGameManager to update a certain collectible playerOverrideID * @notice Sets the player override identifier. * @param _tokenId The token identifier * @param _newOverrideId The new player override identifier */ function setPlayerOverrideId(uint256 _tokenId, uint256 _newOverrideId) public onlyManager whenNotPaused { require (exists(_tokenId)); _updatePlayerOverrideId(_tokenId, _newOverrideId); } /** * @notice Updates the Generation Season Controller. * @dev Allowed to be called by onlyGameManager to update the generation season. * this helps to control the generation of collectible. * @param _season Season UINT representation * @param _value 0-Not allowed, 1-open, >=2 Locked Forever */ function updateGenerationStopTime(uint256 _season, uint8 _value ) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 1 && _value != 0); _updateGenerationSeasonFlag(_season, _value); } /** * @dev set Generation Season Controller, can only be called by Managers._season can be [0,1,2,3..] and * _value can be [0,1,N]. * @notice _value of 1: means generation of collectible is allowed. anything, apart from 1, wont allow generating assets for that season. * @param _season Season UINT representation */ function setGenerationSeasonController(uint256 _season) public onlyManager whenNotPaused { require (generationSeasonController[_season] == 0); _updateGenerationSeasonFlag(_season, 1); } /** * @dev Adding value to DICT helps in showing the season value in getCollectibleDetails * @notice Updates the Generation Season Dict. * @param _season Season UINT representation * @param _value 0-Not allowed,1-allowed */ function updateGenerationDict(uint256 _season, uint64 _value) public onlyManager whenNotPaused { require (generationSeasonDict[_season] <= 1); generationSeasonDict[_season] = _value; } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the MLB player Id from the player attributes * @param _tokenId The token identifier * @return playerId MLB Player Identifier */ function getPlayerId(uint256 _tokenId) external view returns (uint256 playerId) { NFT memory obj = _getAttributesOfToken(_tokenId); playerId = ((obj.attributes.div(100000000000000000)) % 1000); } /** * @dev Helper function to avoid calling getCollectibleDetails * @notice Gets the attachments for an asset * @param _tokenId The token identifier * @return attachments */ function getAssetAttachment(uint256 _tokenId) external view returns (uint256[]) { uint256[] _attachments = nftCollectibleAttachments[_tokenId]; uint256[] attachments; for(uint i=0;i<_attachments.length;i++){ attachments.push(_attachments[i]); } return attachments; } /** * @dev Can only be trigerred by Managers. Updates the earnedBy property of the NFT * @notice Helps in updating the earned _by property of an asset/token. * @param _tokenId asser/token identifier * @param _earnedBy New asset/token DNA */ function updateEarnedBy(uint256 _tokenId, uint256 _earnedBy) public onlyManager whenNotPaused { require (exists(_tokenId)); _updateEarnedBy(_tokenId, _earnedBy); } /** * @dev A batch function to facilitate batching of asset creation. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to To Address */ function batchCreateAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 0, _nftData); } } /** * @dev A batch function to facilitate batching of asset creation for ETH Cards. canCreate modifier * helps in controlling who can call the function * @notice Batch Function to Create Assets * @param _teamId The team identifier * @param _attributes The attributes * @param _playerOverrideId The player override identifier * @param _mlbPlayerId The mlb player identifier * @param _to { parameter_description } */ function batchCreateETHCardAsset( uint8[] _teamId, uint256[] _attributes, uint256[] _playerOverrideId, uint256[] _mlbPlayerId, address[] _to) external canCreate whenNotPaused { require (isBatchSupported); require (_teamId.length > 0 && _attributes.length > 0 && _playerOverrideId.length > 0 && _mlbPlayerId.length > 0 && _to.length > 0); uint256 assetDetails; uint256[5] memory _nftData; for(uint ii = 0; ii < _attributes.length; ii++){ require (_to[ii] != address(0) && _teamId[ii] != 0 && _attributes.length != 0 && _mlbPlayerId[ii] != 0); assetDetails = uint256(uint64(now)); assetDetails |= uint256(getSequenceId(_teamId[ii]))<<64; assetDetails |= uint256(_teamId[ii])<<96; assetDetails |= uint256((_attributes[ii]/1000000000000000000000000000000000000000)-800)<<104; _nftData = [assetDetails, _attributes[ii], 0, _playerOverrideId[ii], _mlbPlayerId[ii]]; _createNFTCollectible(_teamId[ii], _attributes[ii], _to[ii], 2, _nftData); } } /** * @dev Overriden TransferFrom, with the modifier canTransfer which uses our attachment system * @notice Helps in trasnferring assets * @param _from the address sending from * @param _to the address sending to * @param _tokenId The token identifier */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // Asset should not be in play require (checkIsAttached(_tokenId) == 0); require (_from != address(0)); require (_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Facilitates batch trasnfer of collectible with multiple TO Address, depending if batch is supported on contract. * @notice Batch Trasnfer with multpple TO addresses * @param _tokenIds The token identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract * @notice Batch TransferFrom with the same to & from address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchTransferFrom(uint256[] _tokenIds, address _from, address _to) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; transferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom with multiple From and to Addresses * @param _tokenIds The asset identifiers * @param _fromB the address sending from * @param _toB the address sending to */ function multiBatchSafeTransferFrom( uint256[] _tokenIds, address[] _fromB, address[] _toB ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _fromB.length > 0 && _toB.length > 0); uint256 _id; address _to; address _from; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0 && _fromB[i] != 0 && _toB[i] != 0); _id = _tokenIds[i]; _to = _toB[i]; _from = _fromB[i]; safeTransferFrom(_from, _to, _id); } } /** * @dev Facilitates batch trasnfer of collectible, depending if batch is supported on contract. * Checks for collectible 0,address 0 and then performs the transfer * @notice Batch SafeTransferFrom from a single address to another address * @param _tokenIds The asset identifiers * @param _from the address sending from * @param _to the address sending to */ function batchSafeTransferFrom( uint256[] _tokenIds, address _from, address _to ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _from != address(0) && _to != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; safeTransferFrom(_from, _to, _id); } } /** * @notice Batch Function to approve the spender * @dev Helps to approve a batch of collectibles * @param _tokenIds The asset identifiers * @param _spender The spender */ function batchApprove( uint256[] _tokenIds, address _spender ) public { require (isBatchSupported); require (_tokenIds.length > 0 && _spender != address(0)); uint256 _id; for (uint256 i = 0; i < _tokenIds.length; ++i) { require (_tokenIds[i] != 0); _id = _tokenIds[i]; approve(_spender, _id); } } /** * @dev Batch Function to mark spender for approved for all. Does a check * for address(0) and throws if true * @notice Facilitates batch approveAll * @param _spenders The spenders * @param _approved The approved */ function batchSetApprovalForAll( address[] _spenders, bool _approved ) public { require (isBatchSupported); require (_spenders.length > 0); address _spender; for (uint256 i = 0; i < _spenders.length; ++i) { require (address(_spenders[i]) != address(0)); _spender = _spenders[i]; setApprovalForAll(_spender, _approved); } } /** * @dev Function to request Detachment from our Contract * @notice a wallet can request to detach it collectible, so, that it can be used in other third-party contracts. * @param _tokenId The token identifier */ function requestDetachment( uint256 _tokenId ) public { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); uint256 isAttached = checkIsAttached(_tokenId); //If collectible is on a gamecard prevent detachment require(getGameCardId(_tokenId) == 0); require (isAttached >= 1); if(attachedSystemActive == true) { //Checks to see if request was made and if time elapsed if(isAttached > 1 && block.timestamp - isAttached > detachmentTime) { isAttached = 0; } else if(isAttached > 1) { //Forces Tx Fail if time is already set for attachment and not less than detachmentTime require (isAttached == 1); } else { //Is attached, set detachment time and make request to detach // emit AssetUpdated(_tokenId); isAttached = block.timestamp; } } else { isAttached = 0; } updateIsAttached(_tokenId, isAttached); } /** * @dev Function to attach the asset, thus, restricting transfer * @notice Attaches the collectible to our contract * @param _tokenId The token identifier */ function attachAsset( uint256 _tokenId ) public canTransfer(_tokenId) { uint256 isAttached = checkIsAttached(_tokenId); require (isAttached == 0); isAttached = 1; updateIsAttached(_tokenId, isAttached); emit AssetUpdated(_tokenId); } /** * @dev Batch attach function * @param _tokenIds The identifiers */ function batchAttachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { attachAsset(_tokenIds[i]); } } /** * @dev Batch detach function * @param _tokenIds The identifiers */ function batchDetachAssets(uint256[] _tokenIds) public { require (isBatchSupported); for(uint i = 0; i < _tokenIds.length; i++) { requestDetachment(_tokenIds[i]); } } /** * @dev Function to facilitate detachment when contract is paused * @param _tokenId The identifiers */ function requestDetachmentOnPause (uint256 _tokenId) public whenPaused { //Request can only be made by owner or approved address require (isApprovedOrOwner(msg.sender, _tokenId)); updateIsAttached(_tokenId, 0); } /** * @dev Toggle the Attachment Switch * @param _state The state */ function toggleAttachedEnforcement (bool _state) public onlyManager { attachedSystemActive = _state; } /** * @dev Set Attachment Time Period (this restricts user from continuously trigger detachment) * @param _time The time */ function setDetachmentTime (uint256 _time) public onlyManager { //Detactment Time can not be set greater than 2 weeks. require (_time <= 1209600); detachmentTime = uint32(_time); } /** * @dev Detach Asset From System * @param _tokenId The token iddentifier */ function setNFTDetached(uint256 _tokenId) public anyOperator { require (checkIsAttached(_tokenId) > 0); updateIsAttached(_tokenId, 0); } /** * @dev Batch function to detach multiple assets * @param _tokenIds The token identifiers */ function setBatchDetachCollectibles(uint256[] _tokenIds) public anyOperator { uint256 _id; for(uint i = 0; i < _tokenIds.length; i++) { _id = _tokenIds[i]; setNFTDetached(_id); } } /** * @dev Function to update attach value * @param _tokenId The asset id * @param _isAttached Indicates if attached */ function updateIsAttached(uint256 _tokenId, uint256 _isAttached) internal { NFT memory obj = _getAttributesOfToken(_tokenId); obj.isAttached = _isAttached; allNFTs[_tokenId] = obj; emit AssetUpdated(_tokenId); } /** * @dev Facilitates Creating Sale using the Sale Contract. Forces owner check & collectibleId check * @notice Helps a wallet to create a sale using our Sale Contract * @param _tokenId The token identifier * @param _startingPrice The starting price * @param _endingPrice The ending price * @param _duration The duration */ function initiateCreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration) external { require (_tokenId != 0); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address owner = ownerOf(_tokenId); require (owner == msg.sender); // Sale contract checks input sizes require (_startingPrice == _startingPrice); require (_endingPrice == _endingPrice); require (_duration == _duration); require (checkIsAttached(_tokenId) == 0); // One time approval for the tokenID _approveForSale(msg.sender, address(saleManagerAddress), _tokenId); saleManagerAddress.createSale(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender); } /** * @dev Facilitates batch auction of collectibles, and enforeces strict checking on the collectibleId,starting/ending price, duration. * @notice Batch function to put 10 or less collectibles on sale * @param _tokenIds The token identifier * @param _startingPrices The starting price * @param _endingPrices The ending price * @param _durations The duration */ function batchCreateAssetSale(uint256[] _tokenIds, uint256[] _startingPrices, uint256[] _endingPrices, uint256[] _durations) external whenNotPaused { require (_tokenIds.length > 0 && _startingPrices.length > 0 && _endingPrices.length > 0 && _durations.length > 0); // Sale contract checks input sizes for(uint ii = 0; ii < _tokenIds.length; ii++){ // Do not process for tokenId 0 require (_tokenIds[ii] != 0); require (_startingPrices[ii] == _startingPrices[ii]); require (_endingPrices[ii] == _endingPrices[ii]); require (_durations[ii] == _durations[ii]); // If DodgersNFT is already on any sale, this will throw // because it will be owned by the sale contract. address _owner = ownerOf(_tokenIds[ii]); address _msgSender = msg.sender; require (_owner == _msgSender); // Check whether the collectible is inPlay. If inPlay cant put it on Sale require (checkIsAttached(_tokenIds[ii]) == 0); // approve token to for Sale creation _approveForSale(msg.sender, address(saleManagerAddress), _tokenIds[ii]); saleManagerAddress.createSale(_tokenIds[ii], _startingPrices[ii], _endingPrices[ii], _durations[ii], msg.sender); } } }
Lucid Sight, Inc. ERC-721 Collectibles. @title LSNFT - Lucid Sight, Inc. Non-Fungible Token @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.)/
contract LSNFT is ERC721Token { event Created(address owner, uint256 tokenId); struct NFT { uint256 attributes; uint256 currentGameCardId; uint256 mlbGameId; uint256 playerOverrideId; uint256 mlbPlayerId; uint256 earnedBy; uint256 assetDetails; uint256 isAttached; } NFT[] allNFTs; function isLSNFT() public view returns (bool) { return true; } function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); return newLSNFTId; } function _createNFT ( uint256[5] _nftData, address _owner, uint256 _isAttached) internal returns(uint256) { NFT memory _lsnftObj = NFT({ attributes : _nftData[1], currentGameCardId : 0, mlbGameId : _nftData[2], playerOverrideId : _nftData[3], assetDetails: _nftData[0], isAttached: _isAttached, mlbPlayerId: _nftData[4], earnedBy: 0 }); uint256 newLSNFTId = allNFTs.push(_lsnftObj) - 1; _mint(_owner, newLSNFTId); return newLSNFTId; } emit Created(_owner, newLSNFTId); function _getAttributesOfToken(uint256 _tokenId) internal returns(NFT) { NFT storage lsnftObj = allNFTs[_tokenId]; return lsnftObj; } function _approveForSale(address _owner, address _to, uint256 _tokenId) internal { address owner = ownerOf(_tokenId); require (_to != owner); require (_owner == owner || isApprovedForAll(owner, _owner)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(_owner, _to, _tokenId); } } function _approveForSale(address _owner, address _to, uint256 _tokenId) internal { address owner = ownerOf(_tokenId); require (_to != owner); require (_owner == owner || isApprovedForAll(owner, _owner)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(_owner, _to, _tokenId); } } }
7,722,435
[ 1, 48, 5286, 350, 348, 750, 16, 15090, 18, 4232, 39, 17, 27, 5340, 9302, 495, 1040, 18, 225, 511, 13653, 4464, 300, 511, 5286, 350, 348, 750, 16, 15090, 18, 3858, 17, 42, 20651, 1523, 3155, 225, 478, 1561, 566, 2285, 373, 1826, 473, 478, 297, 25842, 1475, 20701, 4365, 69, 261, 48, 5286, 350, 348, 750, 16, 15090, 12998, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 13653, 4464, 353, 4232, 39, 27, 5340, 1345, 288, 203, 21281, 203, 225, 871, 12953, 12, 2867, 3410, 16, 2254, 5034, 1147, 548, 1769, 203, 21281, 21281, 225, 1958, 423, 4464, 288, 203, 565, 2254, 5034, 1677, 31, 203, 203, 565, 2254, 5034, 783, 12496, 6415, 548, 31, 203, 203, 565, 2254, 5034, 12931, 70, 12496, 548, 31, 203, 203, 565, 2254, 5034, 7291, 6618, 548, 31, 203, 203, 565, 2254, 5034, 12931, 70, 12148, 548, 31, 203, 203, 565, 2254, 5034, 425, 1303, 18696, 31, 203, 377, 203, 565, 2254, 5034, 3310, 3790, 31, 203, 377, 203, 565, 2254, 5034, 353, 14890, 31, 203, 225, 289, 203, 203, 225, 423, 4464, 8526, 777, 50, 4464, 87, 31, 203, 203, 225, 445, 353, 3045, 50, 4464, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 389, 2640, 50, 4464, 261, 203, 565, 2254, 5034, 63, 25, 65, 389, 82, 1222, 751, 16, 203, 565, 1758, 389, 8443, 16, 203, 565, 2254, 5034, 389, 291, 14890, 13, 203, 565, 2713, 203, 565, 1135, 12, 11890, 5034, 13, 288, 203, 203, 565, 423, 4464, 3778, 389, 3251, 82, 1222, 2675, 273, 423, 4464, 12590, 203, 3639, 1677, 294, 389, 82, 1222, 751, 63, 21, 6487, 203, 3639, 783, 12496, 6415, 548, 294, 374, 16, 203, 3639, 12931, 70, 12496, 548, 294, 389, 82, 1222, 751, 63, 22, 6487, 203, 3639, 7291, 6618, 548, 294, 389, 82, 1222, 751, 63, 23, 6487, 203, 3639, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.4; import "./Data.sol"; // import "hardhat/console.sol"; library HashOnions { struct Info { bytes32 sourceHashOnion; bytes32 onWorkHashOnion; } } library Fork { struct Info { uint16 workIndex; // 0: zFork, >0: mFork bytes32 onionHead; bytes32 destOnionHead; uint256 allAmount; uint256 length; address lastCommiterAddress; bool needBond; // true is need to settle uint8 verifyStatus; // 0: No verify, 1: Verified - fork is real, 2: Verified - fork is fake } /// @param forkKey fork's key function isExist(mapping(bytes32 => Info) storage self, bytes32 forkKey) internal view returns (bool) { return self[forkKey].length > 0; } /// @param forkKey fork's key function remove(mapping(bytes32 => Info) storage self, bytes32 forkKey) internal { delete self[forkKey]; } /// @param forkKey fork's key /// @param forkInfo fork function update( mapping(bytes32 => Info) storage self, bytes32 forkKey, Info memory forkInfo ) internal { self[forkKey] = forkInfo; } /// Get fork by forkKey. When no exist, report error function getForkEnsure( mapping(bytes32 => Info) storage self, bytes32 forkKey ) internal view returns (Info memory) { Info memory fork = self[forkKey]; require(fork.length > 0, "Fork is null"); //use length return fork; } /// @param chainId Chain's id /// @param hashOnion Equal to fork's first Info.onionHead /// @param index Fork's index function generateForkKey( uint256 chainId, bytes32 hashOnion, uint16 index ) internal pure returns (bytes32) { return keccak256(abi.encode(chainId, hashOnion, index)); } /// @param prevOnionHead Prev onionHead /// @param transferData Transfer's data function generateOnionHead( bytes32 prevOnionHead, Data.TransferData memory transferData ) internal pure returns (bytes32) { return keccak256( abi.encode(prevOnionHead, keccak256(abi.encode(transferData))) ); } /// @param prevDestOnionHead Prev fork destOnionHead /// @param onionHead Current fork onionHead /// @param committer Fork committer function generateDestOnionHead( bytes32 prevDestOnionHead, bytes32 onionHead, address committer ) internal pure returns (bytes32) { return keccak256(abi.encode(prevDestOnionHead, onionHead, committer)); } /// @param chainId Chain's id /// @param maxLength OneFork max length function initialize( mapping(bytes32 => Info) storage self, uint256 chainId, uint256 maxLength ) internal { bytes32 forkKey = generateForkKey(chainId, bytes32(0), 0); require(isExist(self, forkKey) == false); update( self, forkKey, Info(0, bytes32(0), bytes32(0), 0, maxLength, address(0), false, 0) ); } /// @param workForkKey Current work fork's key function createZFork( mapping(bytes32 => Info) storage self, uint256 chainId, bytes32 workForkKey, address dest, uint256 amount, uint256 fee ) internal returns (Info memory _workFork, Info memory _newFork) { // Take out the Fork Info memory workFork = self[workForkKey]; // Create a new Fork Info memory newFork; // set newFork newFork.onionHead = generateOnionHead( workFork.onionHead, Data.TransferData(dest, amount, fee) ); bytes32 newForkKey = generateForkKey(chainId, newFork.onionHead, 0); // Determine whether there is a fork with newForkKey require(isExist(self, newForkKey) == false, "c1"); newFork.destOnionHead = generateDestOnionHead( workFork.destOnionHead, newFork.onionHead, msg.sender ); newFork.allAmount += amount + fee; newFork.length = 1; newFork.lastCommiterAddress = msg.sender; newFork.needBond = true; // storage update(self, newForkKey, newFork); _workFork = workFork; _newFork = newFork; } /// @param _lastOnionHead Before wrong fork's onionHead /// @param _lastDestOnionHead Before wrong fork's destOnionHead function createMFork( mapping(bytes32 => Info) storage self, uint256 chainId, bytes32 _lastOnionHead, bytes32 _lastDestOnionHead, uint16 _index, Data.TransferData calldata _transferData ) internal returns (Info memory) { // Create a new Fork Info memory newFork; // set newFork newFork.onionHead = Fork.generateOnionHead( _lastOnionHead, _transferData ); bytes32 newForkKey = generateForkKey( chainId, newFork.onionHead, _index ); // Determine whether there is a fork with newFork.destOnionHead as the key require(isExist(self, newForkKey) == false, "c1"); newFork.destOnionHead = generateDestOnionHead( _lastDestOnionHead, newFork.onionHead, msg.sender ); newFork.workIndex = _index; newFork.allAmount = _transferData.amount + _transferData.fee; newFork.length = _index + 1; newFork.lastCommiterAddress = msg.sender; newFork.needBond = true; // storage update(self, newForkKey, newFork); return newFork; } /// @param _transferDatas [{destination, amount, fee}...] /// @param _committers committers function getVerifyOnions( Info memory prevFork, Data.TransferData[] calldata _transferDatas, address[] calldata _committers ) internal pure returns (bytes32[] memory onionHeads, bytes32 destOnionHead) { onionHeads = new bytes32[](_transferDatas.length); bytes32 prevOnionHead = prevFork.onionHead; destOnionHead = prevFork.destOnionHead; for (uint256 i; i < _transferDatas.length; i++) { onionHeads[i] = prevOnionHead = generateOnionHead( prevOnionHead, _transferDatas[i] ); destOnionHead = generateDestOnionHead( destOnionHead, onionHeads[i], _committers[i] ); } } // Not verified but not needBond, the fork was earlyBonded function isEarlyBonded(uint8 verifyStatus, bool needBond) internal pure returns (bool) { return verifyStatus == 0 && needBond == false; } }
@param forkKey fork's key @param forkInfo fork
function update( mapping(bytes32 => Info) storage self, bytes32 forkKey, Info memory forkInfo ) internal { self[forkKey] = forkInfo; }
1,841,071
[ 1, 23335, 653, 12515, 1807, 498, 225, 12515, 966, 12515, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 12, 203, 3639, 2874, 12, 3890, 1578, 516, 3807, 13, 2502, 365, 16, 203, 3639, 1731, 1578, 12515, 653, 16, 203, 3639, 3807, 3778, 12515, 966, 203, 565, 262, 2713, 288, 203, 3639, 365, 63, 23335, 653, 65, 273, 12515, 966, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >= 0.5.0 < 0.6.0; import "./Token.sol"; import "https://github.com/oraclize/ethereum-api/oraclizeAPI_0.5.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol"; contract Bank is usingOraclize { using SafeMath for uint; string private orcl_url = "json(http://127.0.0.1:105/SHAK_wei_price).wei"; //string private orcl_url = "json(http://58baa9c87c8b.ngrok.io/SHAK_wei_price).wei"; SHAKtoken private token; // Address where we'll hold all ETH address payable private fundwallet = msg.sender; uint internal rate; uint internal capToken; uint internal remainToken; uint internal tokenTotal; uint public contractBalance; mapping(address => uint) balances; event LogNewOraclizeQuery(string description, string url); event buyTokenEvent(address _from, address _to, uint _amountToken, uint _amountETH); event redeemTokenEvent(address _from, address _to, uint _amountToken, uint _amountETH); event transferTokenEvent(address _from, address _to, uint _amountToken); event fundWithdrawal(address _fund, uint amount); event totalToken(uint _amount); modifier onlyFund { require(msg.sender == fundwallet, "You do not have permission!"); _; } constructor(uint _rate, uint _cap, address payable _fundwallet, SHAKtoken _token) public payable { //Assign where to hold the funds fundwallet = _fundwallet; rate = _rate; capToken = _cap; token = _token; remainToken = _cap; contractBalance = address(this).balance; } function getRate() public view returns (uint) { return rate; } function setRate(uint _rate) public onlyFund { rate = _rate; } function getCap() public view returns (uint) { return capToken; } function setCap(uint _cap) public onlyFund { require(_cap > capToken, "Cannot reduce total token amount."); capToken = _cap; remainToken = _cap.sub(tokenTotal); } function getTokenTotal() public view returns (uint) { return tokenTotal; } function getTokenRemain() public view returns (uint) { return remainToken; } function getcoinBalance () public view returns (uint) { return balances[msg.sender]; } function updateContractBalance () public { contractBalance = address(this).balance; } function setURL (string memory _url) public onlyFund { orcl_url = string(abi.encodePacked("json(", _url, "/SHAK_wei_price).wei")); } function getURL () public view onlyFund returns (string memory) { return orcl_url; } /* Function for external client to buy tokens from us */ function buyToken(address payable _recv) external payable returns (bool, uint) { // check for cap require(tokenTotal < capToken, "Maximum number of token reached!"); // updateRate - Oracalize updateRate(); // calculate amount of tokens from msg.value uint token_amount; uint eth_tx; uint remainder; token_amount = msg.value.div(rate); eth_tx = msg.value.sub(remainder); remainder = msg.value.mod(rate); if(token_amount > remainToken){ token_amount = remainToken; } // mint tokens to _recv SHAKtoken(address(token)).mint(_recv, token_amount); balances[_recv] = balances[_recv].add(token_amount); // update coinTotal tokenTotal = tokenTotal.add(token_amount); remainToken = capToken.sub(tokenTotal); contractBalance = address(this).balance; // return ETH from msg.sender (bool success, ) = msg.sender.call.value(remainder)(""); //return remainder require(success,"Unable to return remainder"); // emit event emit buyTokenEvent(msg.sender, _recv, token_amount, eth_tx); emit totalToken(tokenTotal); // return true if succeed return(true, token_amount); } /* Function for external client to sell tokens back to us */ function redeemToken(address payable _recv, uint amount) external payable returns (bool) { // check whether _source can cover buyBack require(balances[msg.sender] >= amount, "msg.sender doesn't have enough token."); // updateRate - Oracalize updateRate(); // calculate amount of ETH uint eth_tx; eth_tx = amount.mul(rate); require(eth_tx <= address(this).balance, "Unable to buy the specified amount, Please contact fund admin!"); // deduct tokens balances[msg.sender] = balances[msg.sender].sub(amount); // deduct coinTotal tokenTotal = tokenTotal.sub(amount); remainToken = remainToken = capToken.sub(tokenTotal); // send ETH to _recv _recv.transfer(eth_tx); // emit event emit redeemTokenEvent(msg.sender, _recv, amount, eth_tx); emit totalToken(tokenTotal); // returns true if succeed return(true); } /* Function to transfer tokens between clients */ function transferToken(address payable _recv, uint amount) public returns (bool) { // check whether msg.sender can cover transfer require(balances[msg.sender] >= amount, "msg.sender doesn't have enough token."); // deduct from _source balances[msg.sender] = balances[msg.sender].sub(amount); // update _recv balances[_recv] = balances[_recv].add(amount); // emit event emit transferTokenEvent(msg.sender, _recv, amount); // returns true if succeed return (true); } function withdraws(uint _amount) external payable onlyFund returns (bool, uint) { require(msg.value >= address(this).balance, "Unable to withdraws the specified amount."); (bool success, ) = fundwallet.call.value(_amount)(""); require(success,"Unable to withdraws remainder"); emit fundWithdrawal(msg.sender, _amount); return(true, msg.value); } function __callback(bytes32 myid, string memory result, bytes memory proof) public { //This function is executed after the result from Oracalize require(msg.sender == oraclize_cbAddress()); rate = parseInt(result); } function __callback(bytes32 myid, string memory result) public { //This function is executed after the result from Oracalize require(msg.sender == oraclize_cbAddress()); rate = parseInt(result); } function updateRate() public payable { string memory _url; _url = orcl_url; emit LogNewOraclizeQuery("Oraclize query was sent: ", _url); oraclize_query("URL", _url); } function() external payable {} } contract BankDeployer { address public bank_address; address public token_address; constructor(address payable wallet ) public { SHAKtoken token = new SHAKtoken(); token_address = address(token); Bank oBank = new Bank(1, 10000000000000000000, wallet, token); bank_address = address(oBank); token.addMinter(bank_address); token.renounceMinter(); } }
/ check for cap updateRate - Oracalize calculate amount of tokens from msg.value
function buyToken(address payable _recv) external payable returns (bool, uint) { require(tokenTotal < capToken, "Maximum number of token reached!"); updateRate(); uint token_amount; uint eth_tx; uint remainder; token_amount = msg.value.div(rate); eth_tx = msg.value.sub(remainder); remainder = msg.value.mod(rate); if(token_amount > remainToken){ token_amount = remainToken; } balances[_recv] = balances[_recv].add(token_amount); remainToken = capToken.sub(tokenTotal); contractBalance = address(this).balance; emit totalToken(tokenTotal); }
5,366,570
[ 1, 19, 866, 364, 3523, 1089, 4727, 300, 531, 354, 771, 554, 4604, 3844, 434, 2430, 628, 1234, 18, 1132, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30143, 1345, 12, 2867, 8843, 429, 389, 18334, 13, 3903, 8843, 429, 1135, 261, 6430, 16, 2254, 13, 288, 203, 3639, 2583, 12, 2316, 5269, 411, 3523, 1345, 16, 315, 13528, 1300, 434, 1147, 8675, 4442, 1769, 203, 3639, 1089, 4727, 5621, 203, 540, 203, 3639, 2254, 1147, 67, 8949, 31, 203, 3639, 2254, 13750, 67, 978, 31, 203, 3639, 2254, 10022, 31, 203, 3639, 1147, 67, 8949, 273, 1234, 18, 1132, 18, 2892, 12, 5141, 1769, 203, 3639, 13750, 67, 978, 273, 1234, 18, 1132, 18, 1717, 12, 2764, 25407, 1769, 203, 3639, 10022, 273, 1234, 18, 1132, 18, 1711, 12, 5141, 1769, 203, 540, 203, 3639, 309, 12, 2316, 67, 8949, 405, 7232, 1345, 15329, 203, 5411, 1147, 67, 8949, 273, 7232, 1345, 31, 203, 3639, 289, 203, 540, 203, 3639, 324, 26488, 63, 67, 18334, 65, 273, 324, 26488, 63, 67, 18334, 8009, 1289, 12, 2316, 67, 8949, 1769, 203, 540, 203, 3639, 7232, 1345, 273, 3523, 1345, 18, 1717, 12, 2316, 5269, 1769, 203, 3639, 6835, 13937, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 540, 203, 540, 203, 3639, 3626, 2078, 1345, 12, 2316, 5269, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; import "./NameRegistry.sol"; /// @title NameAccessor - manages the endpoints. /// @author Shumpei Koike - <[email protected]> contract NameAccessor { NameRegistry internal _nameRegistry; /// @dev Sets the address of NameRegistry. /// @param nameRegistry address of the NameRegistry constructor(address nameRegistry) { _nameRegistry = NameRegistry(nameRegistry); } /// @dev Prevents calling a function from anyone except the accepted contract. modifier onlyAllowedContract() { require(_nameRegistry.allowedContracts(msg.sender), "AR201"); _; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(owner() == msg.sender, "AR202"); _; } /// @dev Gets the address of NameRegistry function nameRegistryAddress() public view returns (address) { return address(_nameRegistry); } /// @dev Gets the address of Aurora. function auroraAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("Aurora"))); } /// @dev Gets the address of DonationReceipt. function receiptAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("DonationReceipt"))); } /// @dev Gets the address of DonationPost. function postAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("DonationPost"))); } /// @dev Gets the address of RefundRequest. function refundAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("RefundRequest"))); } /// @dev Gets the address of Voucher. function voucherAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("Voucher"))); } /// @dev Gets the address of UltraRareReceipt. function ultraRareAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("UltraRareReceipt"))); } /// @dev Gets the address of Event. function eventAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("Event"))); } /// @dev Gets the address of HologramAccumulator. function accumulatorAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("HologramAccumulator"))); } /// @dev Gets the address of Vault. function vaultAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("Vault"))); } /// @dev Gets the owner address. function owner() public view returns (address) { return _nameRegistry.owner(); } }
@dev Gets the address of Voucher.
function voucherAddress() public view returns (address) { return _nameRegistry.get(keccak256(abi.encodePacked("Voucher"))); }
7,270,386
[ 1, 3002, 326, 1758, 434, 776, 14329, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 331, 14329, 1887, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 202, 202, 2463, 389, 529, 4243, 18, 588, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 2932, 19585, 6, 3719, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xd278A4A079e656a6bCDdD8a3144f9851becB906e/sources/project_/contracts/CompoundTokensERC1155.sol
* @notice Function to craft `Jade` from compounds @param amounts Array of amounts of tokens [Ca, MgFe, Si4O11, OH] @param probability Adittional probability for mint `Jade`/* @dev Used compounds ids/* @dev Pay base price for mint 'Jade' nft/* @dev Additional probability from owned artifacts/* @dev Avoid `Stack to deep` error & write calculate value to `artifactProbability`/* @dev Calculate & transfer CJB to withdrawable account/
function mintJade( uint256[] memory amounts, uint8 probability ) external { require(amounts.length == 4, "JadeBuddhaTokens: Wrong tokens array length"); uint256[] memory ids = new uint256[](4); ids[Ca] = Ca; ids[MgFe] = MgFe; ids[Si4O11] = Si4O11; ids[OH] = OH; require(_checkCompoundAmounts(ids, amounts), "JadeBuddhaTokens: Not enough tokens for this address"); ManageERC20Upgradeable._transferFrom( JadeTokenERC20AddressUpgradeable.getJadeTokenERC20Address(), _msgSender(), address(this), JadeBasePriceUpgradeable.getJadeBasePrice() ); uint8 artifactProbability; { address[] memory artifactsAccounts = new address[](3); artifactsAccounts[0] = _msgSender(); artifactsAccounts[1] = _msgSender(); artifactsAccounts[2] = _msgSender(); uint256[] memory artifactsIds = new uint256[](3); artifactsIds[0] = TEA; artifactsIds[1] = THE_BUDDHA; artifactsIds[2] = JADE_BUDDHA; uint256[] memory amountsOfArtifacts = ManageERC1155Upgradeable._balanceOfBatch( ArtifactsTokensERC1155AddressUpgradeable.getArtifactsTokensERC1155Address(), artifactsAccounts, artifactsIds ); for(uint16 i = 0; i < amountsOfArtifacts.length; i++) { if(amountsOfArtifacts[i] > 0) { artifactProbability += ArtifactsProbabilityBonusUpgradeable.getArtifactProbabilityBonus(artifactsIds[i]); } } } bool isGenerationSuccessful = JadeFactoryUpgradeable._isGenerationSuccessful(jadeTier, probability + artifactProbability); if(probability != 0) { uint256 CJBAmount = JadeProbabilityPriceUpgradeable.calculateProbabilityPrice(probability); ManageERC20Upgradeable._transferFrom( JadeTokenERC20AddressUpgradeable.getJadeTokenERC20Address(), _msgSender(), address(this), CJBAmount ); } if(isGenerationSuccessful) { (uint8 size, uint8 color, uint8 form, uint8 tier, uint8 energy) = JadeFactoryUpgradeable._generateJadeParams(amounts); uint40 metadata = JadeMetadataUpgradeable.encodeMetadata( size, color, form, tier, energy ); uint256 jadeId = Jade + JadeMintedUpgradeable.getJadeMinted(); JadeMintedUpgradeable._increaseMinted(); _mint( _msgSender(), jadeId, 1, "" ); emit JadeFactoryUpgradeable.GenerateJadeSuccess(jadeId, _msgSender(), metadata); _burnBatch( _msgSender(), ids, amounts ); JadeMetadataUpgradeable._setJadeMetadata(jadeId, metadata); emit JadeFactoryUpgradeable.GenerateJadeFail(_msgSender()); } }
5,641,025
[ 1, 2083, 358, 276, 5015, 1375, 46, 2486, 68, 628, 1161, 9284, 565, 30980, 1510, 434, 30980, 434, 2430, 306, 23508, 16, 490, 75, 2954, 16, 27834, 24, 51, 2499, 16, 531, 44, 65, 565, 11331, 4052, 305, 24252, 287, 11331, 364, 312, 474, 1375, 46, 2486, 68, 19, 565, 10286, 1161, 9284, 3258, 19, 565, 13838, 1026, 6205, 364, 312, 474, 296, 46, 2486, 11, 290, 1222, 19, 565, 15119, 11331, 628, 16199, 16259, 19, 565, 17843, 1375, 2624, 358, 4608, 68, 555, 473, 1045, 4604, 460, 358, 1375, 17706, 25598, 68, 19, 565, 9029, 473, 7412, 385, 8877, 358, 598, 9446, 429, 2236, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 46, 2486, 12, 203, 3639, 2254, 5034, 8526, 3778, 30980, 16, 203, 3639, 2254, 28, 11331, 203, 565, 262, 3903, 288, 203, 3639, 2583, 12, 8949, 87, 18, 2469, 422, 1059, 16, 315, 46, 2486, 38, 20567, 3395, 5157, 30, 24668, 2430, 526, 769, 8863, 203, 203, 3639, 2254, 5034, 8526, 3778, 3258, 273, 394, 2254, 5034, 8526, 12, 24, 1769, 203, 3639, 3258, 63, 23508, 65, 273, 23318, 31, 203, 3639, 3258, 63, 49, 75, 2954, 65, 273, 490, 75, 2954, 31, 203, 3639, 3258, 63, 55, 77, 24, 51, 2499, 65, 273, 27834, 24, 51, 2499, 31, 203, 3639, 3258, 63, 51, 44, 65, 273, 531, 44, 31, 203, 203, 3639, 2583, 24899, 1893, 16835, 6275, 87, 12, 2232, 16, 30980, 3631, 315, 46, 2486, 38, 20567, 3395, 5157, 30, 2288, 7304, 2430, 364, 333, 1758, 8863, 203, 203, 3639, 24247, 654, 39, 3462, 10784, 429, 6315, 13866, 1265, 12, 203, 5411, 804, 2486, 1345, 654, 39, 3462, 1887, 10784, 429, 18, 588, 46, 2486, 1345, 654, 39, 3462, 1887, 9334, 7010, 5411, 389, 3576, 12021, 9334, 7010, 5411, 1758, 12, 2211, 3631, 203, 5411, 804, 2486, 2171, 5147, 10784, 429, 18, 588, 46, 2486, 2171, 5147, 1435, 203, 3639, 11272, 203, 540, 203, 3639, 2254, 28, 6462, 25598, 31, 203, 203, 3639, 288, 203, 5411, 1758, 8526, 3778, 16259, 13971, 273, 394, 1758, 8526, 12, 23, 1769, 203, 5411, 16259, 13971, 63, 20, 65, 273, 389, 3576, 12021, 5621, 16259, 13971, 63, 21, 65, 273, 389, 3576, 2 ]
/* Copyright 2017-2018 RigoBlock, Rigo Investment Sagl. 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.21; pragma experimental "v0.5.0"; import { PoolFace as Pool } from "../../Pool/PoolFace.sol"; import { RigoToken } from "../RigoToken/RigoToken.sol"; import { DragoRegistryFace as DragoRegistry } from "../../Registry/DragoRegistry.sol"; import { InflationFace as Inflation } from "../Inflation/InflationFace.sol"; import { SafeMath } from "../../utils/SafeMath/SafeMath.sol"; import { ProofOfPerformanceFace } from "./ProofOfPerformanceFace.sol"; contract ProofOfPerformance is SafeMath, ProofOfPerformanceFace { address public RIGOTOKENADDRESS; address public dragoRegistry; address public rigoblockDao; uint256 public minimumRigo; mapping (uint => PoolPrice) poolPrice; mapping (address => Group) groups; struct PoolPrice { uint highwatermark; } struct Group { uint rewardRatio; } modifier onlyRigoblockDao { require(msg.sender == rigoblockDao); _; } modifier minimumRigoblock { RigoToken rigoToken = RigoToken(RIGOTOKENADDRESS); require(rigoToken.balanceOf(msg.sender) >= minimumRigo); _; } function ProofOfPerformance( address _rigoTokenAddress, address _rigoblockDao, address _dragoRegistry) public { RIGOTOKENADDRESS = _rigoTokenAddress; rigoblockDao = _rigoblockDao; dragoRegistry = _dragoRegistry; } // CORE FUNCTIONS function claimPop(uint _ofPool) external { Inflation infl = Inflation(getMinter()); DragoRegistry registry = DragoRegistry(dragoRegistry); address poolAddress; (poolAddress, , , , , ) = registry.fromId(_ofPool); uint pop = proofOfPerformance(_ofPool); uint price; uint supply; (price, supply) = getPoolPrice(_ofPool); poolPrice[_ofPool].highwatermark = price; require(infl.mintInflation(poolAddress, pop)); } function setRegistry(address _dragoRegistry) external onlyRigoblockDao { dragoRegistry = _dragoRegistry; } function setRigoblockDao(address _rigoblockDao) external onlyRigoblockDao { rigoblockDao = _rigoblockDao; } function setMinimumRigo(uint256 _amount) external onlyRigoblockDao { minimumRigo = _amount; } /// @notice onlyRigoblockDao can set ratio, as it determines /// @notice the split between asset and performance reward for a said group function setRatio(address _ofGroup, uint _ratio) external onlyRigoblockDao { require(_ratio <= 10000); //(from 0 to 10000) groups[_ofGroup].rewardRatio = _ratio; } // CONSTANT PUBLIC FUNCTIONS /// @dev Gets data of a pool /// @param _ofPool Id of the pool /// @return Bool the pool is active /// @return function getPoolData(uint _ofPool) external view returns ( bool active, address thePoolAddress, address thePoolGroup, uint thePoolPrice, uint thePoolSupply, uint poolValue, uint epochReward, uint ratio, uint pop ) { active = isActive(_ofPool); (thePoolAddress, thePoolGroup) = addressFromId(_ofPool); (thePoolPrice, thePoolSupply) = getPoolPrice(_ofPool); ( poolValue, ) = calcPoolValue(_ofPool); epochReward = getEpochReward(_ofPool); ratio = getRatio(_ofPool); pop = proofOfPerformance(_ofPool); } /// @dev Returns the highwatermark of a pool /// @param _ofPool Id of the pool /// @return Value of the all-time-high pool nav function getHwm(uint _ofPool) external view returns (uint) { return poolPrice[_ofPool].highwatermark; } /// @dev Returns two arrays of prices and total supply /// @return Array of addressed of the active pools /// @return Array of the prices of the active pools /// @return Array of the number of tokens of each pool function getPoolPrices() external view returns ( address[] pools, uint[] poolPrices, uint[] totalTokens ) { DragoRegistry registry = DragoRegistry(dragoRegistry); uint length = registry.dragoCount(); for (uint i = 0; i < length; ++i) { bool active = isActive(i); if (!active) { continue; } address fund; address group; (fund, group) = addressFromId(i); pools[i] = fund; Pool pool = Pool(fund); uint thePoolPrice; ( , , thePoolPrice, ) = pool.getData(); poolPrices[i] = thePoolPrice; totalTokens[i] = pool.totalSupply(); } } /// @dev Returns the value of the assets in the rigoblock network /// @return Value of the rigoblock network in wei /// @return Number of active funds function calcNetworkValue() external view returns ( uint networkValue, uint numberOfFunds ) { DragoRegistry registry = DragoRegistry(dragoRegistry); uint length = registry.dragoCount(); for (uint i = 0; i < length; ++i) { bool active = isActive(i); if (!active) { continue; } uint poolValue; (poolValue, ) = calcPoolValue(i); networkValue += poolValue; } return (networkValue, length); } // INTERNAL FUNCTIONS /// @dev Returns the reward factor for a pool /// @param _ofPool Id of the pool /// @return Value of the reward factor function getEpochReward(uint _ofPool) internal view returns (uint) { Inflation inflate = Inflation(getMinter()); address fund; address group; (fund,group) = addressFromId(_ofPool); return inflate.getInflationFactor(group); } /// @dev Returns the split ratio of asset and performance reward /// @param _ofPool Id of the pool /// @return Value of the ratio from 1 to 100 function getRatio(uint _ofPool) internal view returns (uint) { address fund; address group; (fund,group) = addressFromId(_ofPool); return groups[group].rewardRatio; } /// @dev Returns the address of the Inflation contract /// @return Address of the minter/inflation function getMinter() internal view returns (address) { RigoToken token = RigoToken(RIGOTOKENADDRESS); return token.getMinter(); } /// @dev Returns the proof of performance reward for a pool /// @param _ofPool Id of the pool /// @return Value of the reward in Rigo tokens /// @notice epoch reward should be big enough that it /// @notice can be decreased if number of funds increases /// @notice should be at least 10^6 (just as pool base) to start with /// @notice rigo token has 10^18 decimals function proofOfPerformance(uint _ofPool) internal view returns (uint256) { uint highwatermark; if (poolPrice[_ofPool].highwatermark == 0) { highwatermark = 1 ether; } else { highwatermark = poolPrice[_ofPool].highwatermark; } uint poolValue; (poolValue, ) = calcPoolValue(_ofPool); require(poolValue != 0); uint newPrice; uint tokenSupply; (newPrice, tokenSupply) = getPoolPrice(_ofPool); require (newPrice >= highwatermark); uint epochReward = getEpochReward(_ofPool); uint rewardRatio = getRatio(_ofPool); uint prevPrice = highwatermark; uint priceDiff = safeSub(newPrice, prevPrice); uint performanceReward = priceDiff * tokenSupply * epochReward * rewardRatio / 10000 ether; uint assetsReward = poolValue * epochReward * (10000 - rewardRatio) / 10000 ether; return performanceReward + assetsReward; } /// @dev Checks whether a pool is registered and active /// @param _ofPool Id of the pool /// @return Bool the pool is active function isActive(uint _ofPool) internal view returns (bool) { DragoRegistry registry = DragoRegistry(dragoRegistry); address thePool; (thePool, , , , , ) = registry.fromId(_ofPool); if (thePool != address(0)) { return true; } } /// @dev Returns the address and the group of a pool from its id /// @param _ofPool Id of the pool /// @return Address of the target pool /// @return Address of the pool's group function addressFromId(uint _ofPool) internal view returns ( address pool, address group ) { DragoRegistry registry = DragoRegistry(dragoRegistry); address thePool; address theGroup; (thePool, , , , , theGroup) = registry.fromId(_ofPool); pool = thePool; group = theGroup; } /// @dev Returns the price a pool from its id /// @param _ofPool Id of the pool /// @return Price of the pool in wei /// @return Number of tokens of a pool (totalSupply) function getPoolPrice(uint _ofPool) internal view returns ( uint thePoolPrice, uint totalTokens ) { address fund; address group; (fund,group) = addressFromId(_ofPool); address poolAddress = fund; Pool pool = Pool(poolAddress); ( , , thePoolPrice, ) = pool.getData(); totalTokens = pool.totalSupply(); } /// @dev Returns the address and the group of a pool from its id /// @param _ofPool Id of the pool /// @return Address of the target pool /// @return Address of the pool's group function calcPoolValue(uint256 _ofPool) internal view returns ( uint256 aum, bool success ) { uint price; uint supply; (price,supply) = getPoolPrice(_ofPool); return (aum = price * supply / 1000000, true); //1000000 is the base (decimals) } }
@dev Returns the address of the Inflation contract @return Address of the minter/inflation
function getMinter() internal view returns (address) { RigoToken token = RigoToken(RIGOTOKENADDRESS); return token.getMinter(); }
15,809,830
[ 1, 1356, 326, 1758, 434, 326, 657, 2242, 367, 6835, 327, 5267, 434, 326, 1131, 387, 19, 267, 2242, 367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2108, 2761, 1435, 203, 3639, 2713, 1476, 203, 3639, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 534, 17626, 1345, 1147, 273, 534, 17626, 1345, 12, 2259, 43, 1974, 6239, 15140, 1769, 203, 3639, 327, 1147, 18, 588, 49, 2761, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: interfaces/DelegatorInterface.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract DelegatorInterface is DelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public virtual; } abstract contract DelegateInterface is DelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public virtual; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @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 { 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; } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/ActivityBase.sol pragma solidity 0.6.12; contract ActivityBase is Ownable{ using SafeMath for uint256; address public admin; address public marketingFund; // token as the unit of measurement address public WETHToken; // invitee's supply 5% deposit weight to its invitor uint256 public constant INVITEE_WEIGHT = 20; // invitee's supply 10% deposit weight to its invitor uint256 public constant INVITOR_WEIGHT = 10; // The block number when SHARD mining starts. uint256 public startBlock; // dev fund uint256 public userDividendWeight; uint256 public devDividendWeight; address public developerDAOFund; // deposit limit uint256 public amountFeeRateNumerator; uint256 public amountfeeRateDenominator; // contract sender fee rate uint256 public contractFeeRateNumerator; uint256 public contractFeeRateDenominator; // Info of each user is Contract sender mapping (uint256 => mapping (address => bool)) public isUserContractSender; mapping (uint256 => uint256) public poolTokenAmountLimit; function setDividendWeight(uint256 _userDividendWeight, uint256 _devDividendWeight) public virtual{ checkAdmin(); require( _userDividendWeight != 0 && _devDividendWeight != 0, "invalid input" ); userDividendWeight = _userDividendWeight; devDividendWeight = _devDividendWeight; } function setDeveloperDAOFund(address _developerDAOFund) public virtual onlyOwner { developerDAOFund = _developerDAOFund; } function setTokenAmountLimit(uint256 _pid, uint256 _tokenAmountLimit) public virtual { checkAdmin(); poolTokenAmountLimit[_pid] = _tokenAmountLimit; } function setTokenAmountLimitFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); amountFeeRateNumerator = _feeRateNumerator; amountfeeRateDenominator = _feeRateDenominator; } function setContracSenderFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); contractFeeRateNumerator = _feeRateNumerator; contractFeeRateDenominator = _feeRateDenominator; } function setStartBlock(uint256 _startBlock) public virtual onlyOwner { require(startBlock > block.number, "invalid start block"); startBlock = _startBlock; updateAfterModifyStartBlock(_startBlock); } function transferAdmin(address _admin) public virtual { checkAdmin(); admin = _admin; } function setMarketingFund(address _marketingFund) public virtual onlyOwner { marketingFund = _marketingFund; } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal virtual{ } function calculateDividend(uint256 _pending, uint256 _pid, uint256 _userAmount, bool _isContractSender) internal view returns (uint256 _marketingFundDividend, uint256 _devDividend, uint256 _userDividend){ uint256 fee = 0; if(_isContractSender && contractFeeRateDenominator > 0){ fee = _pending.mul(contractFeeRateNumerator).div(contractFeeRateDenominator); _marketingFundDividend = _marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(poolTokenAmountLimit[_pid] > 0 && amountfeeRateDenominator > 0 && _userAmount >= poolTokenAmountLimit[_pid]){ fee = _pending.mul(amountFeeRateNumerator).div(amountfeeRateDenominator); _marketingFundDividend =_marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(devDividendWeight > 0){ fee = _pending.mul(devDividendWeight).div(devDividendWeight.add(userDividendWeight)); _devDividend = _devDividend.add(fee); _pending = _pending.sub(fee); } _userDividend = _pending; } function judgeContractSender(uint256 _pid) internal { if(msg.sender != tx.origin){ isUserContractSender[_pid][msg.sender] = true; } } function checkAdmin() internal view { require(admin == msg.sender, "invalid authorized"); } } // File: interfaces/IInvitation.sol pragma solidity 0.6.12; interface IInvitation{ function acceptInvitation(address _invitor) external; function getInvitation(address _sender) external view returns(address _invitor, address[] memory _invitees, bool _isWithdrawn); } // File: contracts/MarketingMining.sol pragma solidity 0.6.12; contract MarketingMining is ActivityBase{ using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How much token the user has provided. uint256 originWeight; //initial weight uint256 modifiedWeight; //take the invitation relationship into consideration. uint256 revenue; uint256 userDividend; uint256 devDividend; uint256 marketingFundDividend; uint256 rewardDebt; // Reward debt. See explanation below. bool withdrawnState; bool isUsed; } // Info of each pool. struct PoolInfo { uint256 tokenAmount; // lock amount IERC20 token; // uniswapPair contract uint256 allocPoint; uint256 accumulativeDividend; uint256 lastDividendHeight; // last dividend block height uint256 accShardPerWeight; uint256 totalWeight; } uint256 public constant BONUS_MULTIPLIER = 10; // The SHARD TOKEN! IERC20 public SHARD; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => uint256)) public userInviteeTotalAmount; // total invitee weight // Info of each pool. PoolInfo[] public poolInfo; // Total allocation poitns. Must be the sum of all allocation poishard in all pools. uint256 public totalAllocPoint = 0; // SHARD tokens created per block. uint256 public SHDPerBlock = 1045 * (1e16); //get invitation relationship IInvitation public invitation; uint256 public bonusEndBlock; uint256 public totalAvailableDividend; bool public isInitialized; bool public isDepositAvailable; bool public isRevenueWithdrawable; event AddPool(uint256 indexed pid, address tokenAddress); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 weight); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); function initialize( IERC20 _SHARD, IInvitation _invitation, uint256 _bonusEndBlock, uint256 _startBlock, uint256 _SHDPerBlock, address _developerDAOFund, address _marketingFund, address _weth ) public virtual onlyOwner{ require(!isInitialized, "contract has been initialized"); invitation = _invitation; bonusEndBlock = _bonusEndBlock; if (_startBlock < block.number) { startBlock = block.number; } else { startBlock = _startBlock; } SHARD = _SHARD; developerDAOFund = _developerDAOFund; marketingFund = _marketingFund; WETHToken = _weth; if(_SHDPerBlock > 0){ SHDPerBlock = _SHDPerBlock; } userDividendWeight = 4; devDividendWeight = 1; amountFeeRateNumerator = 1; amountfeeRateDenominator = 5; contractFeeRateNumerator = 1; contractFeeRateDenominator = 5; isDepositAvailable = true; isRevenueWithdrawable = false; isInitialized = true; } // Add a new pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _tokenAddress, bool _withUpdate) public virtual { checkAdmin(); if(_withUpdate){ massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; PoolInfo memory newpool = PoolInfo({ token: _tokenAddress, tokenAmount: 0, allocPoint: _allocPoint, lastDividendHeight: lastRewardBlock, accumulativeDividend: 0, accShardPerWeight: 0, totalWeight: 0 }); totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(newpool); emit AddPool(poolInfo.length.sub(1), address(_tokenAddress)); } // Update the given pool's allocation point. Can only be called by the owner. function setAllocationPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public virtual { checkAdmin(); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setSHDPerBlock(uint256 _SHDPerBlock, bool _withUpdate) public virtual { checkAdmin(); if (_withUpdate) { massUpdatePools(); } SHDPerBlock = _SHDPerBlock; } function setIsDepositAvailable(bool _isDepositAvailable) public virtual onlyOwner { isDepositAvailable = _isDepositAvailable; } function setIsRevenueWithdrawable(bool _isRevenueWithdrawable) public virtual onlyOwner { isRevenueWithdrawable = _isRevenueWithdrawable; } // update reward vairables for pools. Be careful of gas spending! function massUpdatePools() public virtual { uint256 poolCount = poolInfo.length; for(uint256 i = 0; i < poolCount; i ++){ updatePoolDividend(i); } } function addAvailableDividend(uint256 _amount, bool _withUpdate) public virtual { if(_withUpdate){ massUpdatePools(); } SHARD.safeTransferFrom(address(msg.sender), address(this), _amount); totalAvailableDividend = totalAvailableDividend.add(_amount); } // update reward vairables for a pool function updatePoolDividend(uint256 _pid) public virtual { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastDividendHeight) { return; } if (pool.tokenAmount == 0) { pool.lastDividendHeight = block.number; return; } uint256 availableDividend = totalAvailableDividend; uint256 multiplier = getMultiplier(pool.lastDividendHeight, block.number); uint256 producedToken = multiplier.mul(SHDPerBlock); producedToken = availableDividend > producedToken? producedToken: availableDividend; if(totalAllocPoint > 0){ uint256 poolDevidend = producedToken.mul(pool.allocPoint).div(totalAllocPoint); if(poolDevidend > 0){ totalAvailableDividend = totalAvailableDividend.sub(poolDevidend); pool.accumulativeDividend = pool.accumulativeDividend.add(poolDevidend); pool.accShardPerWeight = pool.accShardPerWeight.add(poolDevidend.mul(1e12).div(pool.totalWeight)); } } pool.lastDividendHeight = block.number; } function depositETH(uint256 _pid) external payable virtual { require(address(poolInfo[_pid].token) == WETHToken, "invalid token"); updateAfterDeposit(_pid, msg.value); } function withdrawETH(uint256 _pid, uint256 _amount) external virtual { require(address(poolInfo[_pid].token) == WETHToken, "invalid token"); updateAfterwithdraw(_pid, _amount); if(_amount > 0){ (bool success, ) = msg.sender.call{value: _amount}(new bytes(0)); require(success, "Transfer: ETH_TRANSFER_FAILED"); } } function updateAfterDeposit(uint256 _pid, uint256 _amount) internal{ require(isDepositAvailable, "new invest is forbidden"); require(_amount > 0, "invalid amount"); (address invitor, , bool isWithdrawn) = invitation.getInvitation(msg.sender); require(invitor != address(0), "should be accept invitation firstly"); updatePoolDividend(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UserInfo storage userInvitor = userInfo[_pid][invitor]; uint256 existedAmount = user.amount; bool withdrawnState = user.withdrawnState; if(!user.isUsed){ user.isUsed = true; judgeContractSender(_pid); withdrawnState = isWithdrawn; } if(!withdrawnState && userInvitor.amount > 0){ updateUserRevenue(userInvitor, pool); } if(!withdrawnState){ updateInvitorWeight(msg.sender, invitor, _pid, true, _amount, isWithdrawn, withdrawnState); } if(existedAmount > 0){ updateUserRevenue(user, pool); } updateUserWeight(msg.sender, _pid, true, _amount, isWithdrawn); if(!withdrawnState && userInvitor.amount > 0){ userInvitor.rewardDebt = userInvitor.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); } if(!withdrawnState){ user.withdrawnState = isWithdrawn; } user.amount = existedAmount.add(_amount); user.rewardDebt = user.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); pool.tokenAmount = pool.tokenAmount.add(_amount); emit Deposit(msg.sender, _pid, _amount, user.modifiedWeight); } // Deposit tokens to marketing mining for SHD allocation. function deposit(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransferFrom(address(msg.sender), address(this), _amount); updateAfterDeposit(_pid, _amount); } // Withdraw tokens from marketMining. function withdraw(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransfer(address(msg.sender), _amount); updateAfterwithdraw(_pid, _amount); } function updateAfterwithdraw(uint256 _pid, uint256 _amount) internal { (address invitor, , bool isWithdrawn) = invitation.getInvitation(msg.sender); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; bool withdrawnState = user.withdrawnState; uint256 existedAmount = user.amount; require(existedAmount >= _amount, "withdraw: not good"); updatePoolDividend(_pid); uint256 pending = updateUserRevenue(user, pool); UserInfo storage userInvitor = userInfo[_pid][invitor]; if(!withdrawnState && userInvitor.amount > 0){ updateUserRevenue(userInvitor, pool); } if(!withdrawnState){ updateInvitorWeight(msg.sender, invitor, _pid, false, _amount, isWithdrawn, withdrawnState); } updateUserWeight(msg.sender, _pid, false, _amount, isWithdrawn); user.amount = existedAmount.sub(_amount); user.rewardDebt = user.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); user.withdrawnState = isWithdrawn; if(!withdrawnState && userInvitor.amount > 0){ userInvitor.rewardDebt = userInvitor.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); } pool.tokenAmount = pool.tokenAmount.sub(_amount); user.revenue = 0; bool isContractSender = isUserContractSender[_pid][msg.sender]; (uint256 marketingFundDividend, uint256 devDividend, uint256 userDividend) = calculateDividend(pending, _pid, existedAmount, isContractSender); user.userDividend = user.userDividend.add(userDividend); user.devDividend = user.devDividend.add(devDividend); if(marketingFundDividend > 0){ user.marketingFundDividend = user.marketingFundDividend.add(marketingFundDividend); } if(isRevenueWithdrawable){ devDividend = user.devDividend; userDividend = user.userDividend; marketingFundDividend = user.marketingFundDividend; if(devDividend > 0){ safeSHARDTransfer(developerDAOFund, devDividend); } if(userDividend > 0){ safeSHARDTransfer(msg.sender, userDividend); } if(marketingFundDividend > 0){ safeSHARDTransfer(marketingFund, marketingFundDividend); } user.devDividend = 0; user.userDividend = 0; user.marketingFundDividend = 0; } emit Withdraw(msg.sender, _pid, _amount); } // Safe SHD transfer function, just in case if rounding error causes pool to not have enough SHDs. function safeSHARDTransfer(address _to, uint256 _amount) internal { uint256 SHARDBal = SHARD.balanceOf(address(this)); if (_amount > SHARDBal) { SHARD.transfer(_to, SHARDBal); } else { SHARD.transfer(_to, _amount); } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view virtual returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SHDs on frontend. function pendingSHARD(uint256 _pid, address _user) external view virtual returns (uint256 _pending, uint256 _potential, uint256 _blockNumber) { _blockNumber = block.number; (_pending, _potential) = calculatePendingSHARD(_pid, _user); } function pendingSHARDByPids(uint256[] memory _pids, address _user) external view virtual returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber){ uint256 poolCount = _pids.length; _pending = new uint256[](poolCount); _potential = new uint256[](poolCount); _blockNumber = block.number; for(uint i = 0; i < poolCount; i ++){ (_pending[i], _potential[i]) = calculatePendingSHARD(_pids[i], _user); } } function calculatePendingSHARD(uint256 _pid, address _user) private view returns (uint256 _pending, uint256 _potential) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accShardPerWeight = pool.accShardPerWeight; _pending = user.modifiedWeight.mul(accShardPerWeight).div(1e12).sub(user.rewardDebt).add(user.revenue); bool isContractSender = isUserContractSender[_pid][_user]; _potential = _pending; (,,_pending) = calculateDividend(_pending, _pid, user.amount, isContractSender); _pending = _pending.add(user.userDividend); uint256 lpSupply = pool.tokenAmount; if (block.number > pool.lastDividendHeight && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastDividendHeight, block.number); uint256 totalUnupdateToken = multiplier.mul(SHDPerBlock); totalUnupdateToken = totalAvailableDividend > totalUnupdateToken? totalUnupdateToken: totalAvailableDividend; uint256 shardReward = totalUnupdateToken.mul(pool.allocPoint).div(totalAllocPoint); accShardPerWeight = accShardPerWeight.add(shardReward.mul(1e12).div(pool.totalWeight)); } _potential = user.modifiedWeight.mul(accShardPerWeight).div(1e12).sub(user.rewardDebt).add(user.revenue).sub(_potential); (,,_potential) = calculateDividend(_potential, _pid, user.amount, isContractSender); } function getDepositWeight(uint256 _amount) public pure returns(uint256 weight){ return _amount; } function getPoolLength() public view virtual returns(uint256){ return poolInfo.length; } function getPoolInfo(uint256 _pid) public view virtual returns(uint256 _allocPoint, uint256 _accumulativeDividend, uint256 _usersTotalWeight, uint256 _tokenAmount, address _tokenAddress, uint256 _accs){ PoolInfo storage pool = poolInfo[_pid]; _allocPoint = pool.allocPoint; _accumulativeDividend = pool.accumulativeDividend; _usersTotalWeight = pool.totalWeight; _tokenAmount = pool.tokenAmount; _tokenAddress = address(pool.token); _accs = pool.accShardPerWeight; } function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public view virtual returns(uint256[] memory _allocPoint, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _tokenAmount, address[] memory _tokenAddress, uint256[] memory _accs){ uint256 poolCount = _toIndex.sub(_fromIndex).add(1); _allocPoint = new uint256[](poolCount); _accumulativeDividend = new uint256[](poolCount); _usersTotalWeight = new uint256[](poolCount); _tokenAmount = new uint256[](poolCount); _tokenAddress = new address[](poolCount); _accs = new uint256[](poolCount); uint256 startIndex = 0; for(uint i = _fromIndex; i <= _toIndex; i ++){ PoolInfo storage pool = poolInfo[i]; _allocPoint[startIndex] = pool.allocPoint; _accumulativeDividend[startIndex] = pool.accumulativeDividend; _usersTotalWeight[startIndex] = pool.totalWeight; _tokenAmount[startIndex] = pool.tokenAmount; _tokenAddress[startIndex] = address(pool.token); _accs[startIndex] = pool.accShardPerWeight; startIndex ++; } } function getUserInfoByPids(uint256[] memory _pids, address _user) public virtual view returns(uint256[] memory _amount, uint256[] memory _modifiedWeight, uint256[] memory _revenue, uint256[] memory _userDividend, uint256[] memory _rewardDebt) { uint256 poolCount = _pids.length; _amount = new uint256[](poolCount); _modifiedWeight = new uint256[](poolCount); _revenue = new uint256[](poolCount); _userDividend = new uint256[](poolCount); _rewardDebt = new uint256[](poolCount); for(uint i = 0; i < poolCount; i ++){ UserInfo storage user = userInfo[_pids[i]][_user]; _amount[i] = user.amount; _modifiedWeight[i] = user.modifiedWeight; _revenue[i] = user.revenue; _userDividend[i] = user.userDividend; _rewardDebt[i] = user.rewardDebt; } } function updateUserRevenue(UserInfo storage _user, PoolInfo storage _pool) private returns (uint256){ uint256 pending = _user.modifiedWeight.mul(_pool.accShardPerWeight).div(1e12).sub(_user.rewardDebt); _user.revenue = _user.revenue.add(pending); _pool.accumulativeDividend = _pool.accumulativeDividend.sub(pending); return _user.revenue; } function updateInvitorWeight(address _sender, address _invitor, uint256 _pid, bool _isAddAmount, uint256 _amount, bool _isWithdrawn, bool _withdrawnState) private { UserInfo storage user = userInfo[_pid][_sender]; uint256 subInviteeAmount = 0; uint256 addInviteeAmount = 0; if(user.amount > 0 && !_withdrawnState){ subInviteeAmount = user.originWeight; } if(!_isWithdrawn){ if(_isAddAmount){ addInviteeAmount = getDepositWeight(user.amount.add(_amount)); } else{ addInviteeAmount = getDepositWeight(user.amount.sub(_amount)); } } UserInfo storage invitor = userInfo[_pid][_invitor]; PoolInfo storage pool = poolInfo[_pid]; uint256 inviteeAmountOfUserInvitor = userInviteeTotalAmount[_pid][_invitor]; uint256 newInviteeAmountOfUserInvitor = inviteeAmountOfUserInvitor.add(addInviteeAmount).sub(subInviteeAmount); userInviteeTotalAmount[_pid][_invitor] = newInviteeAmountOfUserInvitor; if(invitor.amount > 0){ invitor.modifiedWeight = invitor.modifiedWeight.add(newInviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)) .sub(inviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)); pool.totalWeight = pool.totalWeight.add(newInviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)) .sub(inviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)); } } function updateUserWeight(address _user, uint256 _pid, bool _isAddAmount, uint256 _amount, bool _isWithdrawn) private { UserInfo storage user = userInfo[_pid][_user]; uint256 userOriginModifiedWeight = user.modifiedWeight; uint256 userNewModifiedWeight; if(_isAddAmount){ userNewModifiedWeight = getDepositWeight(_amount.add(user.amount)); } else{ userNewModifiedWeight = getDepositWeight(user.amount.sub(_amount)); } user.originWeight = userNewModifiedWeight; if(!_isWithdrawn){ userNewModifiedWeight = userNewModifiedWeight.add(userNewModifiedWeight.div(INVITOR_WEIGHT)); } uint256 inviteeAmountOfUser = userInviteeTotalAmount[_pid][msg.sender]; userNewModifiedWeight = userNewModifiedWeight.add(inviteeAmountOfUser.div(INVITEE_WEIGHT)); user.modifiedWeight = userNewModifiedWeight; PoolInfo storage pool = poolInfo[_pid]; pool.totalWeight = pool.totalWeight.add(userNewModifiedWeight).sub(userOriginModifiedWeight); } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal override{ uint256 poolLenght = poolInfo.length; for(uint256 i = 0; i < poolLenght; i++){ PoolInfo storage info = poolInfo[i]; info.lastDividendHeight = _newStartBlock; } } } // File: contracts/MarketingMiningDelegate.sol pragma solidity 0.6.12; contract MarketingMiningDelegate is DelegateInterface, MarketingMining { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public override { checkAdmin(); // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public override { checkAdmin(); // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } } }
Deposit tokens to marketing mining for SHD allocation.
function deposit(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransferFrom(address(msg.sender), address(this), _amount); updateAfterDeposit(_pid, _amount); }
83,488
[ 1, 758, 1724, 2430, 358, 13667, 310, 1131, 310, 364, 6122, 40, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 5024, 288, 203, 3639, 2583, 12, 2867, 12, 6011, 966, 63, 67, 6610, 8009, 2316, 13, 480, 678, 1584, 44, 1345, 16, 315, 5387, 4231, 8863, 203, 3639, 467, 654, 39, 3462, 12, 6011, 966, 63, 67, 6610, 8009, 2316, 2934, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 1089, 4436, 758, 1724, 24899, 6610, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x755F47eb3b2c23971E431049A6d415D9d7a66132/sources/StakingNFT.sol
Interface for ERC20 Constructor function reward and NFT
contract MoaiReward is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection, IERC20 _rewardsToken) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 ammountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 private rewardsPerHour = 100000; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].ammountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "you dont own this token" ); } function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].ammountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "you dont own this token" ); } require( nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].ammountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].ammountStaked > 0, "you have no tokens staked!" ); require(stakerAddress[_tokenId] == msg.sender, "you don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].ammountStaked > 0, "you have no tokens staked!" ); require(stakerAddress[_tokenId] == msg.sender, "you don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].ammountStaked > 0, "you have no tokens staked!" ); require(stakerAddress[_tokenId] == msg.sender, "you don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) { index = i; break; } } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].ammountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "you have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].ammountStaked) ) * rewardsPerHour) / 3600); } function availableRewards(address _staker) public view returns (uint256) { uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].ammountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].ammountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].ammountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].ammountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].ammountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].ammountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].ammountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].ammountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].ammountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].ammountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } }
7,080,464
[ 1, 1358, 364, 4232, 39, 3462, 11417, 445, 19890, 471, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 6835, 14987, 10658, 17631, 1060, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 10878, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 2125, 4778, 510, 9477, 31, 203, 3639, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 25259, 31, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1661, 426, 8230, 2 ]
./partial_match/1/0xd558f0C903CcAC458495F0Dc776Dbcc78F1adf79/sources/BatchPreOrder.sol
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension/
contract IERC721Metadata is IERC721 { function name() external view returns (string); function symbol() external view returns (string); function tokenURI(uint256 tokenId) public view returns (string); }
4,435,937
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 1982, 2710, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 654, 39, 27, 5340, 2277, 353, 467, 654, 39, 27, 5340, 288, 203, 225, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 1769, 203, 225, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 1769, 203, 225, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 1080, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xdaFbDBb00b62c7982Bc0AE011cf5209289F7cb5f/sources/browser/TimedCrowdSale.sol
address addr = 0x442C90c625998Fd8048362C82C36209AcEee2538; address payable wallet = address(uint160(addr)); TimedCrowdsale(_openingTime, _closingTime)
contract DemCrowdsale is Crowdsale, CappedCrowdsale, MintedCrowdsale { constructor( uint256 _rate, address payable _wallet, uint256 _cap, ERC20Mintable _token ) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) import "github.com/OpenZeppelin/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol"; { } }
8,133,154
[ 1, 2867, 3091, 273, 374, 92, 6334, 22, 39, 9349, 71, 26, 2947, 2733, 28, 27263, 28, 3028, 28, 5718, 22, 39, 11149, 39, 5718, 3462, 29, 9988, 41, 1340, 2947, 7414, 31, 1758, 8843, 429, 9230, 273, 1758, 12, 11890, 16874, 12, 4793, 10019, 23925, 39, 492, 2377, 5349, 24899, 3190, 310, 950, 16, 389, 19506, 950, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 27744, 39, 492, 2377, 5349, 353, 385, 492, 2377, 5349, 16, 225, 11200, 1845, 39, 492, 2377, 5349, 16, 490, 474, 329, 39, 492, 2377, 5349, 288, 203, 377, 203, 565, 3885, 12, 203, 1377, 203, 3639, 2254, 5034, 389, 5141, 16, 203, 3639, 1758, 8843, 429, 389, 19177, 16, 203, 3639, 2254, 5034, 389, 5909, 16, 203, 3639, 4232, 39, 3462, 49, 474, 429, 389, 2316, 203, 203, 6647, 203, 565, 262, 203, 3639, 1071, 203, 3639, 385, 492, 2377, 5349, 24899, 5141, 16, 389, 19177, 16, 389, 2316, 13, 203, 3639, 11200, 1845, 39, 492, 2377, 5349, 24899, 5909, 13, 203, 203, 5666, 315, 6662, 18, 832, 19, 3678, 62, 881, 84, 292, 267, 19, 94, 881, 84, 292, 267, 17, 30205, 560, 19, 16351, 87, 19, 71, 492, 2377, 5349, 19, 351, 19710, 19, 49, 474, 329, 39, 492, 2377, 5349, 18, 18281, 14432, 203, 565, 288, 203, 540, 203, 565, 289, 203, 203, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x349385F31e20d139449238d49f2b2be342CFbe7f/sources/contracts/NaughtyGiraffes.sol
Friday, April 1, 2022 2:30:00 PM GMT (Friday, April 1, 2022 10:30:00 AM GMT-04:00 DST)
uint256 private _publicStartTime = 1648823400;
12,511,915
[ 1, 42, 1691, 528, 16, 432, 683, 330, 404, 16, 26599, 22, 576, 30, 5082, 30, 713, 23544, 21706, 261, 42, 1691, 528, 16, 432, 683, 330, 404, 16, 26599, 22, 1728, 30, 5082, 30, 713, 20653, 21706, 17, 3028, 30, 713, 463, 882, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 482, 13649, 273, 404, 1105, 5482, 4366, 16010, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x113180ecac90987c7EB2757e608ecF2ab943554C/sources/project:/contracts/PurplecoinCrowdsale.sol
* @dev Prevents a contract from calling itself, directly or indirectly. Calling a `nonReentrant` function from another `nonReentrant` function is not supported. It is possible to prevent this from happening by making the `nonReentrant` function external, and make it call a `private` function that does the actual work./
modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); }
4,830,603
[ 1, 25828, 87, 279, 6835, 628, 4440, 6174, 16, 5122, 578, 16807, 715, 18, 21020, 279, 1375, 5836, 426, 8230, 970, 68, 445, 628, 4042, 1375, 5836, 426, 8230, 970, 68, 445, 353, 486, 3260, 18, 2597, 353, 3323, 358, 5309, 333, 628, 5865, 310, 635, 10480, 326, 1375, 5836, 426, 8230, 970, 68, 445, 3903, 16, 471, 1221, 518, 745, 279, 1375, 1152, 68, 445, 716, 1552, 326, 3214, 1440, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 389, 24594, 4789, 1011, 404, 31, 203, 3639, 2254, 5034, 1191, 4789, 273, 389, 24594, 4789, 31, 203, 3639, 389, 31, 203, 3639, 2583, 12, 3729, 4789, 422, 389, 24594, 4789, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xD781b8126F857A2073D5d0DD3D2903253DAA46bD/sources/src/token/ERC721/base/ERC721ABaseInternal.sol
* @dev Returns the total number of tokens burned./
function _totalBurned() internal view virtual returns (uint256) { return ERC721SupplyStorage.layout().burnCounter; }
4,637,403
[ 1, 1356, 326, 2078, 1300, 434, 2430, 18305, 329, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4963, 38, 321, 329, 1435, 2713, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 4232, 39, 27, 5340, 3088, 1283, 3245, 18, 6741, 7675, 70, 321, 4789, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // TODO: remove ERC165 import {IERC1155} from './IERC1155.sol'; import {IERC1155Receiver} from './IERC1155Receiver.sol'; import {ERC1155BaseStorage} from './ERC1155BaseStorage.sol'; import {ERC165} from '../../introspection/ERC165.sol'; import {AddressUtils} from '../../utils/AddressUtils.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC165 { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf ( address account, uint id ) override public view returns (uint) { require(account != address(0), 'ERC1155: balance query for the zero address'); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch ( address[] memory accounts, uint[] memory ids ) override public view returns (uint[] memory) { require(accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch'); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; uint[] memory batchBalances = new uint[](accounts.length); for (uint i; i < accounts.length; i++) { require(accounts[i] != address(0), 'ERC1155: batch balance query for the zero address'); batchBalances[i] = balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll ( address account, address operator ) override public view returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll ( address operator, bool status ) override public { require(msg.sender != operator, 'ERC1155: setting approval status for self'); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][operator] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom ( address from, address to, uint id, uint amount, bytes memory data ) override public { require(from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved'); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom ( address from, address to, uint[] memory ids, uint[] memory amounts, bytes memory data ) override public { require(from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved'); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implemenation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint ( address account, uint id, uint amount, bytes memory data ) virtual internal { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer(msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); mapping (address => uint) storage balances = ERC1155BaseStorage.layout().balances[id]; balances[account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint ( address account, uint id, uint amount, bytes memory data ) virtual internal { _doSafeTransferAcceptanceCheck(msg.sender, address(0), account, id, amount, data); _mint(account, id, amount, data); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implemenation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch ( address account, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal { require(account != address(0), 'ERC1155: mint to the zero address'); require(ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch'); _beforeTokenTransfer(msg.sender, address(0), account, ids, amounts, data); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; for (uint i; i < ids.length; i++) { uint id = ids[i]; balances[id][account] += amounts[i]; } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch ( address account, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal { _doSafeBatchTransferAcceptanceCheck(msg.sender, address(0), account, ids, amounts, data); _mintBatch(account, ids, amounts, data); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn ( address account, uint id, uint amount ) virtual internal { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer(msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ''); mapping (address => uint) storage balances = ERC1155BaseStorage.layout().balances[id]; require(balances[account] >= amount, 'ERC1155: burn amount exceeds balances'); balances[account] -= amount; emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch ( address account, uint[] memory ids, uint[] memory amounts ) virtual internal { require(account != address(0), 'ERC1155: burn from the zero address'); require(ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch'); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; for (uint i; i < ids.length; i++) { uint id = ids[i]; require(balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance'); balances[id][account] -= amounts[i]; } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implemenation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer ( address operator, address sender, address recipient, uint id, uint amount, bytes memory data ) virtual internal { require(recipient != address(0), 'ERC1155: transfer to the zero address'); _beforeTokenTransfer(operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; uint256 senderBalance = balances[id][sender]; require(senderBalance >= amount, 'ERC1155: insufficient balances for transfer'); unchecked { balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer ( address operator, address sender, address recipient, uint id, uint amount, bytes memory data ) virtual internal { _doSafeTransferAcceptanceCheck(operator, sender, recipient, id, amount, data); _transfer(operator, sender, recipient, id, amount, data); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implemenation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch ( address operator, address sender, address recipient, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal { require(recipient != address(0), 'ERC1155: transfer to the zero address'); require(ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch'); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; for (uint i; i < ids.length; i++) { uint token = ids[i]; uint amount = amounts[i]; uint256 senderBalance = balances[token][sender]; require(senderBalance >= amount, 'ERC1155: insufficient balances for transfer'); unchecked { balances[token][sender] = senderBalance - amount; } balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch ( address operator, address sender, address recipient, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal { _doSafeBatchTransferAcceptanceCheck(operator, sender, recipient, ids, amounts, data); _transferBatch(operator, sender, recipient, ids, amounts, data); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray ( uint element ) private pure returns (uint[] memory) { uint[] memory array = new uint[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _doSafeTransferAcceptanceCheck ( address operator, address from, address to, uint id, uint amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _doSafeBatchTransferAcceptanceCheck ( address operator, address from, address to, uint[] memory ids, uint[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implemenation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer ( address operator, address from, address to, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal {} }
* @notice mint batch of tokens for given address @dev ERC1155Receiver implemenation is not checked @param account beneficiary of minting @param ids list of token IDs @param amounts list of quantities of tokens to mint @param data data payload/
function _mintBatch ( address account, uint[] memory ids, uint[] memory amounts, bytes memory data ) virtual internal { require(account != address(0), 'ERC1155: mint to the zero address'); require(ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch'); _beforeTokenTransfer(msg.sender, address(0), account, ids, amounts, data); mapping (uint => mapping (address => uint)) storage balances = ERC1155BaseStorage.layout().balances; for (uint i; i < ids.length; i++) { uint id = ids[i]; balances[id][account] += amounts[i]; } emit TransferBatch(msg.sender, address(0), account, ids, amounts); }
909,027
[ 1, 81, 474, 2581, 434, 2430, 364, 864, 1758, 225, 4232, 39, 2499, 2539, 12952, 1646, 3269, 275, 367, 353, 486, 5950, 225, 2236, 27641, 74, 14463, 814, 434, 312, 474, 310, 225, 3258, 666, 434, 1147, 7115, 225, 30980, 666, 434, 10251, 1961, 434, 2430, 358, 312, 474, 225, 501, 501, 2385, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 81, 474, 4497, 261, 203, 565, 1758, 2236, 16, 203, 565, 2254, 8526, 3778, 3258, 16, 203, 565, 2254, 8526, 3778, 30980, 16, 203, 565, 1731, 3778, 501, 203, 225, 262, 5024, 2713, 288, 203, 565, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 296, 654, 39, 2499, 2539, 30, 312, 474, 358, 326, 3634, 1758, 8284, 203, 565, 2583, 12, 2232, 18, 2469, 422, 30980, 18, 2469, 16, 296, 654, 39, 2499, 2539, 30, 3258, 471, 30980, 769, 13484, 8284, 203, 203, 565, 389, 5771, 1345, 5912, 12, 3576, 18, 15330, 16, 1758, 12, 20, 3631, 2236, 16, 3258, 16, 30980, 16, 501, 1769, 203, 203, 565, 2874, 261, 11890, 516, 2874, 261, 2867, 516, 2254, 3719, 2502, 324, 26488, 273, 4232, 39, 2499, 2539, 2171, 3245, 18, 6741, 7675, 70, 26488, 31, 203, 203, 565, 364, 261, 11890, 277, 31, 277, 411, 3258, 18, 2469, 31, 277, 27245, 288, 203, 1377, 2254, 612, 273, 3258, 63, 77, 15533, 203, 1377, 324, 26488, 63, 350, 6362, 4631, 65, 1011, 30980, 63, 77, 15533, 203, 565, 289, 203, 203, 565, 3626, 12279, 4497, 12, 3576, 18, 15330, 16, 1758, 12, 20, 3631, 2236, 16, 3258, 16, 30980, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./libraries/UniswapV2Library.sol"; import "./libraries/TransferHelper.sol"; import "./interfaces/uniswap/IUniswapV2Factory.sol"; import "./interfaces/uniswap/IUniswapV2Pair.sol"; import "./interfaces/IDPexRouter.sol"; import "./interfaces/IDPexFeeAggregator.sol"; import "./interfaces/IWETH.sol"; import "./abstracts/Governable.sol"; import "./abstracts/SafeGas.sol"; contract DPexRouter is Initializable, IDPexRouter, Governable, SafeGas { using SafeMath for uint; address public override factory; address public override WETH; address public override feeAggregator; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'DPexRouter: EXPIRED'); _; } modifier onlyAggregator() { require(feeAggregator == msg.sender, "DPexRouter: ONLY_FEE_AGGREGATOR"); _; } function initialize(address _factory, address _WETH, address _gov_contract, address _aggregator) public initializer { super.initialize(_gov_contract); factory = _factory; WETH = _WETH; feeAggregator = _aggregator; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'DPexRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'DPexRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override useCHI ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IUniswapV2Pair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable useCHI ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = UniswapV2Library.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IUniswapV2Pair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override useCHI ensure(deadline) returns (uint amountA, uint amountB) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'DPexRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'DPexRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override useCHI ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, 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 virtual override useCHI returns (uint amountA, uint amountB) { _permit(tokenA, tokenB, liquidity, deadline, approveMax, v, r ,s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function _permit( address tokenA, address tokenB, uint liquidity, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) internal { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override useCHI returns (uint amountToken, uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override useCHI ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override useCHI returns (uint amountETH) { address pair = UniswapV2Library.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override useCHI ensure(deadline) returns (uint[] memory amounts) { amounts = getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); (uint256 amount,) = subtractFee(path[0], amounts[0]); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amount ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override useCHI ensure(deadline) returns (uint[] memory amounts) { amounts = getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'DPexRouter: EXCESSIVE_INPUT_AMOUNT'); (uint256 amount,) = subtractFee(path[0], amounts[0]); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amount ); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable useCHI ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'DPexRouter: INVALID_PATH'); amounts = getAmountsOut(msg.value, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); (uint256 amount,) = subtractFeeWETH(amounts[0]); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amount)); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override useCHI ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'DPexRouter: INVALID_PATH'); amounts = getAmountsIn(amountOut, path); require(amounts[0] <= amountInMax, 'DPexRouter: EXCESSIVE_INPUT_AMOUNT'); amounts = _swapTokensForETH(amounts, path, to); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override useCHI ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'DPexRouter: INVALID_PATH'); amounts = getAmountsOut(amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); amounts = _swapTokensForETH(amounts, path, to); } function _swapTokensForETH(uint[] memory amounts, address[] calldata path, address to) internal returns (uint[] memory) { (uint256 amount, uint256 fee) = subtractFee(path[0], amounts[0]); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amount ); _swap(amounts, path, address(this)); if (fee == 0) { (uint256 amountOut,) = subtractFeeWETH(amounts[amounts.length - 1]); amounts[amounts.length - 1] = amountOut; } IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); return amounts; } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable useCHI ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'DPexRouter: INVALID_PATH'); amounts = getAmountsIn(amountOut, path); require(amounts[0] <= msg.value, 'DPexRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amounts[0]}(); (uint256 amount,) = subtractFeeWETH(amounts[0]); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amount)); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amount) TransferHelper.safeTransferETH(msg.sender, msg.value - amount); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = UniswapV2Library.sortTokens(input, output); IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override useCHI ensure(deadline) { (uint256 amount,) = subtractFee(path[0], amountIn); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amount ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable useCHI ensure(deadline) { require(path[0] == WETH, 'DPexRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); (uint256 amount,) = subtractFeeWETH(amountIn); assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amount)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override useCHI ensure(deadline) { require(path[path.length - 1] == WETH, 'DPexRouter: INVALID_PATH'); (uint256 amount, uint256 fee) = subtractFee(path[0], amountIn); TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amount ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); if (fee == 0) { (amountOut, fee) = subtractFeeWETH(amountOut); } IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return UniswapV2Library.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public view virtual override returns (uint amountOut) { require(amountIn > 0, 'DPexRouter: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DPexRouter: INSUFFICIENT_LIQUIDITY'); (, uint256 amountInWithFee) = IDPexFeeAggregator(feeAggregator).calculateFee(amountIn); amountInWithFee = amountInWithFee.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public view virtual override returns (uint amountIn) { require(amountOut > 0, 'DPexRouter: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'DPexRouter: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); (, uint256 amountOutWithFee) = IDPexFeeAggregator(feeAggregator).calculateFee(amountOut); uint denominator = reserveOut.sub(amountOutWithFee).mul(997); amountIn = (numerator / denominator).add(1); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { require(path.length >= 2, 'DPexRouter: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { require(path.length >= 2, 'DPexRouter: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } /** Aggregator function helpers */ /** * @notice changes the fee aggregator * @param aggregator new aggregator address */ function setfeeAggregator(address aggregator) external override onlyGovernor { require(aggregator != address(0), "DPexRouter: FEE_AGGREGATOR_NO_ADDRESS"); feeAggregator = aggregator; } function subtractFee(address token, uint256 amount) internal virtual returns(uint256 amountLeft, uint256 fee) { uint256 balanceBefore = IERC20(token).balanceOf(feeAggregator); (fee, amountLeft) = IDPexFeeAggregator(feeAggregator).calculateFee(token, amount); if (fee > 0) { TransferHelper.safeTransferFrom(token, msg.sender, feeAggregator, fee); IDPexFeeAggregator(feeAggregator).addTokenFee( token, IERC20(token).balanceOf(feeAggregator).sub(balanceBefore) ); } } function subtractFeeWETH(uint256 amount) internal virtual returns(uint256 amountLeft, uint256 fee) { uint256 balanceBefore = IERC20(WETH).balanceOf(feeAggregator); (fee, amountLeft) = IDPexFeeAggregator(feeAggregator).calculateFee(WETH, amount); if (fee > 0) { assert(IWETH(WETH).transfer(feeAggregator, fee)); IDPexFeeAggregator(feeAggregator).addTokenFee( WETH, IERC20(WETH).balanceOf(feeAggregator).sub(balanceBefore) ); } } function swapAggregatorToken( uint amountIn, address[] calldata path, address to ) external virtual override useCHI onlyAggregator returns (uint256) { TransferHelper.safeTransferFrom( path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); return IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore); } }
**** ADD LIQUIDITY **** create the pair if it doesn't exist yet
function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { IUniswapV2Factory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'DPexRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'DPexRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } }
2,518,696
[ 1, 8355, 8961, 53, 3060, 4107, 225, 752, 326, 3082, 309, 518, 3302, 1404, 1005, 4671, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1289, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 3844, 1880, 281, 2921, 16, 203, 3639, 2254, 3844, 38, 25683, 16, 203, 3639, 2254, 3844, 2192, 267, 16, 203, 3639, 2254, 3844, 38, 2930, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 3844, 37, 16, 2254, 3844, 38, 13, 288, 203, 3639, 309, 261, 45, 984, 291, 91, 438, 58, 22, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 37, 16, 1147, 38, 13, 422, 1758, 12, 20, 3719, 288, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 6848, 2934, 2640, 4154, 12, 2316, 37, 16, 1147, 38, 1769, 203, 3639, 289, 203, 3639, 261, 11890, 20501, 37, 16, 2254, 20501, 38, 13, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 588, 607, 264, 3324, 12, 6848, 16, 1147, 37, 16, 1147, 38, 1769, 203, 3639, 309, 261, 455, 6527, 37, 422, 374, 597, 20501, 38, 422, 374, 13, 288, 203, 5411, 261, 8949, 37, 16, 3844, 38, 13, 273, 261, 8949, 1880, 281, 2921, 16, 3844, 38, 25683, 1769, 203, 5411, 2254, 3844, 5315, 337, 2840, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 6889, 12, 8949, 1880, 281, 2921, 16, 20501, 37, 16, 20501, 38, 1769, 203, 5411, 309, 261, 8949, 5315, 337, 2840, 1648, 3844, 38, 25683, 13, 288, 203, 7734, 2583, 12, 8949, 5315, 337, 2840, 1545, 3844, 38, 2930, 16, 296, 8640, 338, 8259, 30, 2120, 6639, 42, 1653, 7266, 2 ]
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract COSHATokenCNY { // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 1 * 10 ** (10 + uint256(decimals)); // Update total supply with the decimal amount initialSupply = totalSupply; balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = "COSHATokenCNY"; // Set the name for display purposes symbol = "C-CNY"; // Set the symbol for display purposes tokenName = name; tokenSymbol = symbol; } /** * 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 { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on 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 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 on 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 on 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; } }
Update total supply with the decimal amount
totalSupply = initialSupply * 1 * 10 ** (10 + uint256(decimals));
1,565,547
[ 1, 1891, 2078, 14467, 598, 326, 6970, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 273, 2172, 3088, 1283, 380, 404, 380, 1728, 2826, 261, 2163, 397, 2254, 5034, 12, 31734, 10019, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.7.6; /** * @title Liquity. * @dev Lending & Borrowing. */ import { BorrowerOperationsLike, TroveManagerLike, StabilityPoolLike, StakingLike, CollateralSurplusLike, LqtyTokenLike } from "./interface.sol"; import { Stores } from "../../common/stores.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; abstract contract LiquityResolver is Events, Helpers { /* Begin: Trove */ /** * @dev Deposit native ETH and borrow LUSD * @notice Opens a Trove by depositing ETH and borrowing LUSD * @param depositAmount The amount of ETH to deposit * @param maxFeePercentage The maximum borrow fee that this transaction should permit * @param borrowAmount The amount of LUSD to borrow * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getIds Optional (default: 0) Optional storage slot to get deposit & borrow amounts stored using other spells * @param setIds Optional (default: 0) Optional storage slot to set deposit & borrow amounts to be used in future spells */ function open( uint depositAmount, uint maxFeePercentage, uint borrowAmount, address upperHint, address lowerHint, uint[] memory getIds, uint[] memory setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) { depositAmount = getUint(getIds[0], depositAmount); borrowAmount = getUint(getIds[1], borrowAmount); depositAmount = depositAmount == uint(-1) ? address(this).balance : depositAmount; borrowerOperations.openTrove{value: depositAmount}( maxFeePercentage, borrowAmount, upperHint, lowerHint ); setUint(setIds[0], depositAmount); setUint(setIds[1], borrowAmount); _eventName = "LogOpen(address,uint256,uint256,uint256,uint256[],uint256[])"; _eventParam = abi.encode(address(this), maxFeePercentage, depositAmount, borrowAmount, getIds, setIds); } /** * @dev Repay LUSD debt from the DSA account's LUSD balance, and withdraw ETH to DSA * @notice Closes a Trove by repaying LUSD debt * @param setId Optional storage slot to store the ETH withdrawn from the Trove */ function close(uint setId) external payable returns (string memory _eventName, bytes memory _eventParam) { uint collateral = troveManager.getTroveColl(address(this)); borrowerOperations.closeTrove(); // Allow other spells to use the collateral released from the Trove setUint(setId, collateral); _eventName = "LogClose(address,uint256)"; _eventParam = abi.encode(address(this), setId); } /** * @dev Deposit ETH to Trove * @notice Increase Trove collateral (collateral Top up) * @param amount Amount of ETH to deposit into Trove * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getId Optional storage slot to retrieve the ETH from * @param setId Optional storage slot to set the ETH deposited */ function deposit( uint amount, address upperHint, address lowerHint, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amount = getUint(getId, amount); _amount = _amount == uint(-1) ? address(this).balance : _amount; borrowerOperations.addColl{value: _amount}(upperHint, lowerHint); setUint(setId, _amount); _eventName = "LogDeposit(address,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), _amount, getId, setId); } /** * @dev Withdraw ETH from Trove * @notice Move Trove collateral from Trove to DSA * @param amount Amount of ETH to move from Trove to DSA * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getId Optional storage slot to get the amount of ETH to withdraw * @param setId Optional storage slot to store the withdrawn ETH in */ function withdraw( uint amount, address upperHint, address lowerHint, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amount = getUint(getId, amount); _amount = _amount == uint(-1) ? troveManager.getTroveColl(address(this)) : _amount; borrowerOperations.withdrawColl(_amount, upperHint, lowerHint); setUint(setId, _amount); _eventName = "LogWithdraw(address,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), _amount, getId, setId); } /** * @dev Mints LUSD tokens * @notice Borrow LUSD via an existing Trove * @param maxFeePercentage The maximum borrow fee that this transaction should permit * @param amount Amount of LUSD to borrow * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getId Optional storage slot to retrieve the amount of LUSD to borrow * @param setId Optional storage slot to store the final amount of LUSD borrowed */ function borrow( uint maxFeePercentage, uint amount, address upperHint, address lowerHint, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amount = getUint(getId, amount); borrowerOperations.withdrawLUSD(maxFeePercentage, _amount, upperHint, lowerHint); setUint(setId, _amount); _eventName = "LogBorrow(address,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), _amount, getId, setId); } /** * @dev Send LUSD to repay debt * @notice Repay LUSD Trove debt * @param amount Amount of LUSD to repay * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getId Optional storage slot to retrieve the amount of LUSD from * @param setId Optional storage slot to store the final amount of LUSD repaid */ function repay( uint amount, address upperHint, address lowerHint, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amount = getUint(getId, amount); if (_amount == uint(-1)) { uint _lusdBal = lusdToken.balanceOf(address(this)); uint _totalDebt = troveManager.getTroveDebt(address(this)); _amount = _lusdBal > _totalDebt ? _totalDebt : _lusdBal; } borrowerOperations.repayLUSD(_amount, upperHint, lowerHint); setUint(setId, _amount); _eventName = "LogRepay(address,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), _amount, getId, setId); } /** * @dev Increase or decrease Trove ETH collateral and LUSD debt in one transaction * @notice Adjust Trove debt and/or collateral * @param maxFeePercentage The maximum borrow fee that this transaction should permit * @param withdrawAmount Amount of ETH to withdraw * @param depositAmount Amount of ETH to deposit * @param borrowAmount Amount of LUSD to borrow * @param repayAmount Amount of LUSD to repay * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list * @param getIds Optional Get Ids for deposit, withdraw, borrow & repay * @param setIds Optional Set Ids for deposit, withdraw, borrow & repay */ function adjust( uint maxFeePercentage, uint depositAmount, uint withdrawAmount, uint borrowAmount, uint repayAmount, address upperHint, address lowerHint, uint[] memory getIds, uint[] memory setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) { AdjustTrove memory adjustTrove; adjustTrove.maxFeePercentage = maxFeePercentage; depositAmount = getUint(getIds[0], depositAmount); adjustTrove.depositAmount = depositAmount == uint(-1) ? address(this).balance : depositAmount; withdrawAmount = getUint(getIds[1], withdrawAmount); adjustTrove.withdrawAmount = withdrawAmount == uint(-1) ? troveManager.getTroveColl(address(this)) : withdrawAmount; adjustTrove.borrowAmount = getUint(getIds[2], borrowAmount); repayAmount = getUint(getIds[3], repayAmount); if (repayAmount == uint(-1)) { uint _lusdBal = lusdToken.balanceOf(address(this)); uint _totalDebt = troveManager.getTroveDebt(address(this)); repayAmount = _lusdBal > _totalDebt ? _totalDebt : _lusdBal; } adjustTrove.repayAmount = repayAmount; adjustTrove.isBorrow = borrowAmount > 0; borrowerOperations.adjustTrove{value: adjustTrove.depositAmount}( adjustTrove.maxFeePercentage, adjustTrove.withdrawAmount, adjustTrove.borrowAmount, adjustTrove.isBorrow, upperHint, lowerHint ); setUint(setIds[0], adjustTrove.depositAmount); setUint(setIds[1], adjustTrove.withdrawAmount); setUint(setIds[2], adjustTrove.borrowAmount); setUint(setIds[3], adjustTrove.repayAmount); _eventName = "LogAdjust(address,uint256,uint256,uint256,uint256,uint256,uint256[],uint256[])"; _eventParam = abi.encode(address(this), maxFeePercentage, adjustTrove.depositAmount, adjustTrove.withdrawAmount, adjustTrove.borrowAmount, adjustTrove.repayAmount, getIds, setIds); } /** * @dev Withdraw remaining ETH balance from user's redeemed Trove to their DSA * @param setId Optional storage slot to store the ETH claimed * @notice Claim remaining collateral from Trove */ function claimCollateralFromRedemption(uint setId) external payable returns(string memory _eventName, bytes memory _eventParam) { uint amount = collateralSurplus.getCollateral(address(this)); borrowerOperations.claimCollateral(); setUint(setId, amount); _eventName = "LogClaimCollateralFromRedemption(address,uint256,uint256)"; _eventParam = abi.encode(address(this), amount, setId); } /* End: Trove */ /* Begin: Stability Pool */ /** * @dev Deposit LUSD into Stability Pool * @notice Deposit LUSD into Stability Pool * @param amount Amount of LUSD to deposit into Stability Pool * @param frontendTag Address of the frontend to make this deposit against (determines the kickback rate of rewards) * @param getDepositId Optional storage slot to retrieve the amount of LUSD from * @param setDepositId Optional storage slot to store the final amount of LUSD deposited * @param setEthGainId Optional storage slot to store any ETH gains in * @param setLqtyGainId Optional storage slot to store any LQTY gains in */ function stabilityDeposit( uint amount, address frontendTag, uint getDepositId, uint setDepositId, uint setEthGainId, uint setLqtyGainId ) external payable returns (string memory _eventName, bytes memory _eventParam) { amount = getUint(getDepositId, amount); amount = amount == uint(-1) ? lusdToken.balanceOf(address(this)) : amount; uint ethGain = stabilityPool.getDepositorETHGain(address(this)); uint lqtyBalanceBefore = lqtyToken.balanceOf(address(this)); stabilityPool.provideToSP(amount, frontendTag); uint lqtyBalanceAfter = lqtyToken.balanceOf(address(this)); uint lqtyGain = sub(lqtyBalanceAfter, lqtyBalanceBefore); setUint(setDepositId, amount); setUint(setEthGainId, ethGain); setUint(setLqtyGainId, lqtyGain); _eventName = "LogStabilityDeposit(address,uint256,uint256,uint256,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), amount, ethGain, lqtyGain, frontendTag, getDepositId, setDepositId, setEthGainId, setLqtyGainId); } /** * @dev Withdraw user deposited LUSD from Stability Pool * @notice Withdraw LUSD from Stability Pool * @param amount Amount of LUSD to withdraw from Stability Pool * @param getWithdrawId Optional storage slot to retrieve the amount of LUSD to withdraw from * @param setWithdrawId Optional storage slot to store the withdrawn LUSD * @param setEthGainId Optional storage slot to store any ETH gains in * @param setLqtyGainId Optional storage slot to store any LQTY gains in */ function stabilityWithdraw( uint amount, uint getWithdrawId, uint setWithdrawId, uint setEthGainId, uint setLqtyGainId ) external payable returns (string memory _eventName, bytes memory _eventParam) { amount = getUint(getWithdrawId, amount); amount = amount == uint(-1) ? stabilityPool.getCompoundedLUSDDeposit(address(this)) : amount; uint ethGain = stabilityPool.getDepositorETHGain(address(this)); uint lqtyBalanceBefore = lqtyToken.balanceOf(address(this)); stabilityPool.withdrawFromSP(amount); uint lqtyBalanceAfter = lqtyToken.balanceOf(address(this)); uint lqtyGain = sub(lqtyBalanceAfter, lqtyBalanceBefore); setUint(setWithdrawId, amount); setUint(setEthGainId, ethGain); setUint(setLqtyGainId, lqtyGain); _eventName = "LogStabilityWithdraw(address,uint256,uint256,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), amount, ethGain, lqtyGain, getWithdrawId, setWithdrawId, setEthGainId, setLqtyGainId); } /** * @dev Increase Trove collateral by sending Stability Pool ETH gain to user's Trove * @notice Moves user's ETH gain from the Stability Pool into their Trove * @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list * @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list */ function stabilityMoveEthGainToTrove( address upperHint, address lowerHint ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint amount = stabilityPool.getDepositorETHGain(address(this)); stabilityPool.withdrawETHGainToTrove(upperHint, lowerHint); _eventName = "LogStabilityMoveEthGainToTrove(address,uint256)"; _eventParam = abi.encode(address(this), amount); } /* End: Stability Pool */ /* Begin: Staking */ /** * @dev Sends LQTY tokens from user to Staking Pool * @notice Stake LQTY in Staking Pool * @param amount Amount of LQTY to stake * @param getStakeId Optional storage slot to retrieve the amount of LQTY to stake * @param setStakeId Optional storage slot to store the final staked amount (can differ if requested with max balance: uint(-1)) * @param setEthGainId Optional storage slot to store any ETH gains * @param setLusdGainId Optional storage slot to store any LUSD gains */ function stake( uint amount, uint getStakeId, uint setStakeId, uint setEthGainId, uint setLusdGainId ) external payable returns (string memory _eventName, bytes memory _eventParam) { amount = getUint(getStakeId, amount); amount = amount == uint(-1) ? lqtyToken.balanceOf(address(this)) : amount; uint ethGain = staking.getPendingETHGain(address(this)); uint lusdGain = staking.getPendingLUSDGain(address(this)); staking.stake(amount); setUint(setStakeId, amount); setUint(setEthGainId, ethGain); setUint(setLusdGainId, lusdGain); _eventName = "LogStake(address,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), amount, getStakeId, setStakeId, setEthGainId, setLusdGainId); } /** * @dev Sends LQTY tokens from Staking Pool to user * @notice Unstake LQTY in Staking Pool * @param amount Amount of LQTY to unstake * @param getUnstakeId Optional storage slot to retrieve the amount of LQTY to unstake * @param setUnstakeId Optional storage slot to store the unstaked LQTY * @param setEthGainId Optional storage slot to store any ETH gains * @param setLusdGainId Optional storage slot to store any LUSD gains */ function unstake( uint amount, uint getUnstakeId, uint setUnstakeId, uint setEthGainId, uint setLusdGainId ) external payable returns (string memory _eventName, bytes memory _eventParam) { amount = getUint(getUnstakeId, amount); amount = amount == uint(-1) ? staking.stakes(address(this)) : amount; uint ethGain = staking.getPendingETHGain(address(this)); uint lusdGain = staking.getPendingLUSDGain(address(this)); staking.unstake(amount); setUint(setUnstakeId, amount); setUint(setEthGainId, ethGain); setUint(setLusdGainId, lusdGain); _eventName = "LogUnstake(address,uint256,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), amount, getUnstakeId, setUnstakeId, setEthGainId, setLusdGainId); } /** * @dev Sends ETH and LUSD gains from Staking to user * @notice Claim ETH and LUSD gains from Staking * @param setEthGainId Optional storage slot to store the claimed ETH * @param setLusdGainId Optional storage slot to store the claimed LUSD */ function claimStakingGains( uint setEthGainId, uint setLusdGainId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint ethGain = staking.getPendingETHGain(address(this)); uint lusdGain = staking.getPendingLUSDGain(address(this)); // Gains are claimed when a user's stake is adjusted, so we unstake 0 to trigger the claim staking.unstake(0); setUint(setEthGainId, ethGain); setUint(setLusdGainId, lusdGain); _eventName = "LogClaimStakingGains(address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), ethGain, lusdGain, setEthGainId, setLusdGainId); } /* End: Staking */ } contract ConnectV2Liquity is LiquityResolver { string public name = "Liquity-v1"; }
* @dev Send LUSD to repay debt @notice Repay LUSD Trove debt @param amount Amount of LUSD to repay @param upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list @param lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list @param getId Optional storage slot to retrieve the amount of LUSD from @param setId Optional storage slot to store the final amount of LUSD repaid/
function repay( uint amount, address upperHint, address lowerHint, uint getId, uint setId ) external payable returns (string memory _eventName, bytes memory _eventParam) { uint _amount = getUint(getId, amount); if (_amount == uint(-1)) { uint _lusdBal = lusdToken.balanceOf(address(this)); uint _totalDebt = troveManager.getTroveDebt(address(this)); _amount = _lusdBal > _totalDebt ? _totalDebt : _lusdBal; } borrowerOperations.repayLUSD(_amount, upperHint, lowerHint); setUint(setId, _amount); _eventName = "LogRepay(address,uint256,uint256,uint256)"; _eventParam = abi.encode(address(this), _amount, getId, setId); }
1,044,732
[ 1, 3826, 511, 3378, 40, 358, 2071, 528, 18202, 88, 225, 868, 10239, 511, 3378, 40, 399, 303, 537, 18202, 88, 225, 3844, 16811, 434, 511, 3378, 40, 358, 2071, 528, 225, 3854, 7002, 5267, 434, 326, 399, 303, 537, 13378, 326, 3854, 2489, 434, 1625, 326, 729, 1807, 399, 303, 537, 1410, 2037, 10982, 316, 326, 5901, 399, 303, 537, 666, 225, 2612, 7002, 5267, 434, 326, 399, 303, 537, 13378, 326, 2612, 2489, 434, 1625, 326, 729, 1807, 399, 303, 537, 1410, 2037, 10982, 316, 326, 5901, 399, 303, 537, 666, 225, 2634, 4055, 2502, 4694, 358, 4614, 326, 3844, 434, 511, 3378, 40, 628, 225, 10446, 4055, 2502, 4694, 358, 1707, 326, 727, 3844, 434, 511, 3378, 40, 2071, 20736, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2071, 528, 12, 203, 3639, 2254, 3844, 16, 203, 3639, 1758, 3854, 7002, 16, 203, 3639, 1758, 2612, 7002, 16, 203, 3639, 2254, 2634, 16, 203, 3639, 2254, 10446, 203, 565, 262, 3903, 8843, 429, 1135, 261, 1080, 3778, 389, 2575, 461, 16, 1731, 3778, 389, 2575, 786, 13, 225, 288, 203, 3639, 2254, 389, 8949, 273, 336, 5487, 12, 26321, 16, 3844, 1769, 203, 203, 3639, 309, 261, 67, 8949, 422, 2254, 19236, 21, 3719, 288, 203, 5411, 2254, 389, 80, 407, 72, 38, 287, 273, 328, 407, 72, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 2254, 389, 4963, 758, 23602, 273, 23432, 537, 1318, 18, 588, 56, 303, 537, 758, 23602, 12, 2867, 12, 2211, 10019, 203, 5411, 389, 8949, 273, 389, 80, 407, 72, 38, 287, 405, 389, 4963, 758, 23602, 692, 389, 4963, 758, 23602, 294, 389, 80, 407, 72, 38, 287, 31, 203, 3639, 289, 203, 203, 3639, 29759, 264, 9343, 18, 266, 10239, 48, 3378, 40, 24899, 8949, 16, 3854, 7002, 16, 2612, 7002, 1769, 203, 203, 3639, 444, 5487, 12, 542, 548, 16, 389, 8949, 1769, 203, 203, 3639, 389, 2575, 461, 273, 315, 1343, 426, 10239, 12, 2867, 16, 11890, 5034, 16, 11890, 5034, 16, 11890, 5034, 2225, 31, 203, 3639, 389, 2575, 786, 273, 24126, 18, 3015, 12, 2867, 12, 2211, 3631, 389, 8949, 16, 2634, 16, 10446, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x8575c62fb06f8D6eFa6BC65E3A80844A6C4092Ae/sources/project_/contracts/Evaluations/MinValue.sol
todo check for multiple winner
function getCurrentPayouts( ChallengeManager.LeaderboardItem[] calldata leaderboard, uint256 prizePool ) external pure override returns (int256[] memory) { int256[] memory payouts = new int256[](leaderboard.length); payouts[0] = ABDKMath64x64.fromUInt(prizePool); for (uint256 i = 1; i < payouts.length; i++) { payouts[i] = 0; } return payouts; }
3,842,002
[ 1, 9012, 866, 364, 3229, 5657, 1224, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5175, 52, 2012, 87, 12, 203, 565, 1680, 8525, 1318, 18, 15254, 3752, 1180, 8526, 745, 892, 30052, 16, 203, 565, 2254, 5034, 846, 554, 2864, 203, 225, 262, 3903, 16618, 3849, 1135, 261, 474, 5034, 8526, 3778, 13, 288, 203, 565, 509, 5034, 8526, 3778, 293, 2012, 87, 273, 394, 509, 5034, 8526, 12, 27863, 3752, 18, 2469, 1769, 203, 565, 293, 2012, 87, 63, 20, 65, 273, 10336, 3398, 10477, 1105, 92, 1105, 18, 2080, 14342, 12, 683, 554, 2864, 1769, 203, 203, 565, 364, 261, 11890, 5034, 277, 273, 404, 31, 277, 411, 293, 2012, 87, 18, 2469, 31, 277, 27245, 288, 203, 1377, 293, 2012, 87, 63, 77, 65, 273, 374, 31, 203, 565, 289, 203, 203, 565, 327, 293, 2012, 87, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright 2017-2020, bZeroX, LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } contract IERC20 { string public name; uint8 public decimals; string public symbol; 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 approve(address _spender, uint256 _value) public returns (bool); function transfer(address _to, 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); } contract IWethERC20 is IWeth, IERC20 {} contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; } /** * @dev Library for managing loan sets * * 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. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * 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. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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(isOwner(), "unauthorized"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset uint256 owedPerDay; // interest owed per day for all loans of asset uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term) uint256 paidTotal; // total interest paid so far for asset uint256 updatedTimestamp; // last update } } contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan uint256 depositTotal; // total escrowed interest for loan uint256 updatedTimestamp; // last update } } contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } interface IPriceFeeds { function queryRate( address sourceToken, address destToken) external view returns (uint256 rate, uint256 precision); function queryPrecision( address sourceToken, address destToken) external view returns (uint256 precision); function queryReturn( address sourceToken, address destToken, uint256 sourceAmount) external view returns (uint256 destAmount); function checkPriceDisagreement( address sourceToken, address destToken, uint256 sourceAmount, uint256 destAmount, uint256 maxSlippage) external view returns (uint256 sourceToDestSwapRate); function amountInEth( address Token, uint256 amount) external view returns (uint256 ethAmount); function getMaxDrawdown( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (uint256); function getCurrentMarginAndCollateralSize( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralInEthAmount); function getCurrentMargin( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount) external view returns (uint256 currentMargin, uint256 collateralToLoanRate); function shouldLiquidate( address loanToken, address collateralToken, uint256 loanAmount, uint256 collateralAmount, uint256 maintenanceMargin) external view returns (bool); function getFastGasPrice( address payToken) external view returns (uint256); } contract ProtocolTokenUser is State { using SafeERC20 for IERC20; function _withdrawProtocolToken( address receiver, uint256 amount) internal returns (address, uint256) { uint256 withdrawAmount = amount; uint256 tokenBalance = protocolTokenHeld; if (withdrawAmount > tokenBalance) { withdrawAmount = tokenBalance; } if (withdrawAmount == 0) { return (vbzrxTokenAddress, 0); } protocolTokenHeld = tokenBalance .sub(withdrawAmount); IERC20(vbzrxTokenAddress).safeTransfer( receiver, withdrawAmount ); return (vbzrxTokenAddress, withdrawAmount); } } contract FeesEvents { event PayLendingFee( address indexed payer, address indexed token, uint256 amount ); event PayTradingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event PayBorrowingFee( address indexed payer, address indexed token, bytes32 indexed loanId, uint256 amount ); event EarnReward( address indexed receiver, address indexed token, bytes32 indexed loanId, uint256 amount ); } contract FeesHelper is State, ProtocolTokenUser, FeesEvents { using SafeERC20 for IERC20; // calculate trading fee function _getTradingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(tradingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // calculate loan origination fee function _getBorrowingFee( uint256 feeTokenAmount) internal view returns (uint256) { return feeTokenAmount .mul(borrowingFeePercent) .divCeil(WEI_PERCENT_PRECISION); } // settle trading fee function _payTradingFee( address user, bytes32 loanId, address feeToken, uint256 tradingFee) internal { if (tradingFee != 0) { tradingFeeTokensHeld[feeToken] = tradingFeeTokensHeld[feeToken] .add(tradingFee); emit PayTradingFee( user, feeToken, loanId, tradingFee ); _payFeeReward( user, loanId, feeToken, tradingFee ); } } // settle loan origination fee function _payBorrowingFee( address user, bytes32 loanId, address feeToken, uint256 borrowingFee) internal { if (borrowingFee != 0) { borrowingFeeTokensHeld[feeToken] = borrowingFeeTokensHeld[feeToken] .add(borrowingFee); emit PayBorrowingFee( user, feeToken, loanId, borrowingFee ); _payFeeReward( user, loanId, feeToken, borrowingFee ); } } // settle lender (interest) fee function _payLendingFee( address user, address feeToken, uint256 lendingFee) internal { if (lendingFee != 0) { lendingFeeTokensHeld[feeToken] = lendingFeeTokensHeld[feeToken] .add(lendingFee); emit PayLendingFee( user, feeToken, lendingFee ); //// NOTE: Lenders do not receive a fee reward //// } } // settles and pays borrowers based on the fees generated by their interest payments function _settleFeeRewardForInterestExpense( LoanInterest storage loanInterestLocal, bytes32 loanId, address feeToken, address user, uint256 interestTime) internal { uint256 updatedTimestamp = loanInterestLocal.updatedTimestamp; uint256 interestExpenseFee; if (updatedTimestamp != 0) { // this represents the fee generated by a borrower's interest payment interestExpenseFee = interestTime .sub(updatedTimestamp) .mul(loanInterestLocal.owedPerDay) .mul(lendingFeePercent) .div(1 days * WEI_PERCENT_PRECISION); } loanInterestLocal.updatedTimestamp = interestTime; if (interestExpenseFee != 0) { _payFeeReward( user, loanId, feeToken, interestExpenseFee ); } } // pay protocolToken reward to user function _payFeeReward( address user, bytes32 loanId, address feeToken, uint256 feeAmount) internal { // The protocol is designed to allow positions and loans to be closed, if for whatever reason // the price lookup is failing, returning 0, or is otherwise paused. Therefore, we allow this // call to fail silently, rather than revert, to allow the transaction to continue without a // BZRX token reward. uint256 rewardAmount; address _priceFeeds = priceFeeds; (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).queryReturn.selector, feeToken, bzrxTokenAddress, // price rewards using BZRX price rather than vesting token price feeAmount / 2 // 50% of fee value ) ); assembly { if eq(success, 1) { rewardAmount := mload(add(data, 32)) } } if (rewardAmount != 0) { address rewardToken; (rewardToken, rewardAmount) = _withdrawProtocolToken( user, rewardAmount ); if (rewardAmount != 0) { protocolTokenPaid = protocolTokenPaid .add(rewardAmount); emit EarnReward( user, rewardToken, loanId, rewardAmount ); } } } } contract VaultController is Constants { using SafeERC20 for IERC20; event VaultDeposit( address indexed asset, address indexed from, uint256 amount ); event VaultWithdraw( address indexed asset, address indexed to, uint256 amount ); function vaultEtherDeposit( address from, uint256 value) internal { IWethERC20 _wethToken = wethToken; _wethToken.deposit.value(value)(); emit VaultDeposit( address(_wethToken), from, value ); } function vaultEtherWithdraw( address to, uint256 value) internal { if (value != 0) { IWethERC20 _wethToken = wethToken; uint256 balance = address(this).balance; if (value > balance) { _wethToken.withdraw(value - balance); } Address.sendValue(to, value); emit VaultWithdraw( address(_wethToken), to, value ); } } function vaultDeposit( address token, address from, uint256 value) internal { if (value != 0) { IERC20(token).safeTransferFrom( from, address(this), value ); emit VaultDeposit( token, from, value ); } } function vaultWithdraw( address token, address to, uint256 value) internal { if (value != 0) { IERC20(token).safeTransfer( to, value ); emit VaultWithdraw( token, to, value ); } } function vaultTransfer( address token, address from, address to, uint256 value) internal { if (value != 0) { if (from == address(this)) { IERC20(token).safeTransfer( to, value ); } else { IERC20(token).safeTransferFrom( from, to, value ); } } } function vaultApprove( address token, address to, uint256 value) internal { if (value != 0 && IERC20(token).allowance(address(this), to) != 0) { IERC20(token).safeApprove(to, 0); } IERC20(token).safeApprove(to, value); } } contract InterestUser is State, VaultController, FeesHelper { using SafeERC20 for IERC20; function _payInterest( address lender, address interestToken) internal { LenderInterest storage lenderInterestLocal = lenderInterest[lender][interestToken]; uint256 interestOwedNow = 0; if (lenderInterestLocal.owedPerDay != 0 && lenderInterestLocal.updatedTimestamp != 0) { interestOwedNow = block.timestamp .sub(lenderInterestLocal.updatedTimestamp) .mul(lenderInterestLocal.owedPerDay) .div(1 days); lenderInterestLocal.updatedTimestamp = block.timestamp; if (interestOwedNow > lenderInterestLocal.owedTotal) interestOwedNow = lenderInterestLocal.owedTotal; if (interestOwedNow != 0) { lenderInterestLocal.paidTotal = lenderInterestLocal.paidTotal .add(interestOwedNow); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .sub(interestOwedNow); _payInterestTransfer( lender, interestToken, interestOwedNow ); } } else { lenderInterestLocal.updatedTimestamp = block.timestamp; } } function _payInterestTransfer( address lender, address interestToken, uint256 interestOwedNow) internal { uint256 lendingFee = interestOwedNow .mul(lendingFeePercent) .divCeil(WEI_PERCENT_PRECISION); _payLendingFee( lender, interestToken, lendingFee ); // transfers the interest to the lender, less the interest fee vaultWithdraw( interestToken, lender, interestOwedNow .sub(lendingFee) ); } } contract LiquidationHelper is State { function _getLiquidationAmounts( uint256 principal, uint256 collateral, uint256 currentMargin, uint256 maintenanceMargin, uint256 collateralToLoanRate, uint256 incentivePercent) internal view returns (uint256 maxLiquidatable, uint256 maxSeizable) { if (currentMargin > maintenanceMargin || collateralToLoanRate == 0) { return (maxLiquidatable, maxSeizable); } else if (currentMargin <= incentivePercent) { return (principal, collateral); } uint256 desiredMargin = maintenanceMargin .add(5 ether); // 5 percentage points above maintenance // maxLiquidatable = ((1 + desiredMargin)*principal - collateralToLoanRate*collateral) / (desiredMargin - incentivePercent) maxLiquidatable = desiredMargin .add(WEI_PERCENT_PRECISION) .mul(principal) .div(WEI_PERCENT_PRECISION); maxLiquidatable = maxLiquidatable .sub( collateral .mul(collateralToLoanRate) .div(WEI_PRECISION) ); maxLiquidatable = maxLiquidatable .mul(WEI_PERCENT_PRECISION) .div( desiredMargin .sub(incentivePercent) ); if (maxLiquidatable > principal) { maxLiquidatable = principal; } // maxSeizable = maxLiquidatable * (1 + incentivePercent) / collateralToLoanRate maxSeizable = maxLiquidatable .mul( incentivePercent .add(WEI_PERCENT_PRECISION) ); maxSeizable = maxSeizable .div(collateralToLoanRate) .div(100); if (maxSeizable > collateral) { maxSeizable = collateral; } return (maxLiquidatable, maxSeizable); } } contract SwapsEvents { event LoanSwap( bytes32 indexed loanId, address indexed sourceToken, address indexed destToken, address borrower, uint256 sourceAmount, uint256 destAmount ); event ExternalSwap( address indexed user, address indexed sourceToken, address indexed destToken, uint256 sourceAmount, uint256 destAmount ); } interface ISwapsImpl { function dexSwap( address sourceTokenAddress, address destTokenAddress, address receiverAddress, address returnToSenderAddress, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount) external returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed); function dexExpectedRate( address sourceTokenAddress, address destTokenAddress, uint256 sourceTokenAmount) external view returns (uint256); } contract SwapsUser is State, SwapsEvents, FeesHelper { function _loanSwap( bytes32 loanId, address sourceToken, address destToken, address user, uint256 minSourceTokenAmount, uint256 maxSourceTokenAmount, uint256 requiredDestTokenAmount, bool bypassFee, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 sourceToDestSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall( [ sourceToken, destToken, address(this), // receiver address(this), // returnToSender user ], [ minSourceTokenAmount, maxSourceTokenAmount, requiredDestTokenAmount ], loanId, bypassFee, loanDataBytes ); // will revert if swap size too large _checkSwapSize(sourceToken, sourceTokenAmountUsed); // will revert if disagreement found sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement( sourceToken, destToken, sourceTokenAmountUsed, destTokenAmountReceived, maxDisagreement ); emit LoanSwap( loanId, sourceToken, destToken, user, sourceTokenAmountUsed, destTokenAmountReceived ); } function _swapsCall( address[5] memory addrs, uint256[3] memory vals, bytes32 loanId, bool miscBool, // bypassFee bytes memory loanDataBytes) internal returns (uint256, uint256) { //addrs[0]: sourceToken //addrs[1]: destToken //addrs[2]: receiver //addrs[3]: returnToSender //addrs[4]: user //vals[0]: minSourceTokenAmount //vals[1]: maxSourceTokenAmount //vals[2]: requiredDestTokenAmount require(vals[0] != 0, "sourceAmount == 0"); uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; uint256 tradingFee; if (!miscBool) { // bypassFee if (vals[2] == 0) { // condition: vals[0] will always be used as sourceAmount tradingFee = _getTradingFee(vals[0]); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, addrs[0], // sourceToken tradingFee ); vals[0] = vals[0] .sub(tradingFee); } } else { // condition: unknown sourceAmount will be used tradingFee = _getTradingFee(vals[2]); if (tradingFee != 0) { vals[2] = vals[2] .add(tradingFee); } } } if (vals[1] == 0) { vals[1] = vals[0]; } else { require(vals[0] <= vals[1], "min greater than max"); } require(loanDataBytes.length == 0, "invalid state"); (destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall_internal( addrs, vals ); if (vals[2] == 0) { // there's no minimum destTokenAmount, but all of vals[0] (minSourceTokenAmount) must be spent, and amount spent can't exceed vals[0] require(sourceTokenAmountUsed == vals[0], "swap too large to fill"); if (tradingFee != 0) { sourceTokenAmountUsed = sourceTokenAmountUsed + tradingFee; // will never overflow } } else { // there's a minimum destTokenAmount required, but sourceTokenAmountUsed won't be greater than vals[1] (maxSourceTokenAmount) require(sourceTokenAmountUsed <= vals[1], "swap fill too large"); require(destTokenAmountReceived >= vals[2], "insufficient swap liquidity"); if (tradingFee != 0) { _payTradingFee( addrs[4], // user loanId, // loanId, addrs[1], // destToken tradingFee ); destTokenAmountReceived = destTokenAmountReceived - tradingFee; // will never overflow } } return (destTokenAmountReceived, sourceTokenAmountUsed); } function _swapsCall_internal( address[5] memory addrs, uint256[3] memory vals) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed) { bytes memory data = abi.encodeWithSelector( ISwapsImpl(swapsImpl).dexSwap.selector, addrs[0], // sourceToken addrs[1], // destToken addrs[2], // receiverAddress addrs[3], // returnToSenderAddress vals[0], // minSourceTokenAmount vals[1], // maxSourceTokenAmount vals[2] // requiredDestTokenAmount ); bool success; (success, data) = swapsImpl.delegatecall(data); require(success, "swap failed"); (destTokenAmountReceived, sourceTokenAmountUsed) = abi.decode(data, (uint256, uint256)); } function _swapsExpectedReturn( address sourceToken, address destToken, uint256 sourceTokenAmount) internal view returns (uint256) { uint256 tradingFee = _getTradingFee(sourceTokenAmount); if (tradingFee != 0) { sourceTokenAmount = sourceTokenAmount .sub(tradingFee); } uint256 sourceToDestRate = ISwapsImpl(swapsImpl).dexExpectedRate( sourceToken, destToken, sourceTokenAmount ); uint256 sourceToDestPrecision = IPriceFeeds(priceFeeds).queryPrecision( sourceToken, destToken ); return sourceTokenAmount .mul(sourceToDestRate) .div(sourceToDestPrecision); } function _checkSwapSize( address tokenAddress, uint256 amount) internal view { uint256 _maxSwapSize = maxSwapSize; if (_maxSwapSize != 0) { uint256 amountInEth; if (tokenAddress == address(wethToken)) { amountInEth = amount; } else { amountInEth = IPriceFeeds(priceFeeds).amountInEth(tokenAddress, amount); } require(amountInEth <= _maxSwapSize, "swap too large"); } } } interface ILoanPool { function tokenPrice() external view returns (uint256 price); function borrowInterestRate() external view returns (uint256); function totalAssetSupply() external view returns (uint256); } contract ITokenHolderLike { function balanceOf(address _who) public view returns (uint256); function freeUpTo(uint256 value) public returns (uint256); function freeFromUpTo(address from, uint256 value) public returns (uint256); } contract GasTokenUser { ITokenHolderLike constant public gasToken = ITokenHolderLike(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); ITokenHolderLike constant public tokenHolder = ITokenHolderLike(0x55Eb3DD3f738cfdda986B8Eff3fa784477552C61); modifier usesGasToken(address holder) { if (holder == address(0)) { holder = address(tokenHolder); } if (gasToken.balanceOf(holder) != 0) { uint256 gasCalcValue = gasleft(); _; gasCalcValue = (_gasUsed(gasCalcValue) + 14154) / 41947; if (holder == address(tokenHolder)) { tokenHolder.freeUpTo( gasCalcValue ); } else { tokenHolder.freeFromUpTo( holder, gasCalcValue ); } } else { _; } } function _gasUsed( uint256 startingGas) internal view returns (uint256) { return 21000 + startingGas - gasleft() + 16 * msg.data.length; } } contract LoanClosingsEvents { event CloseWithDeposit( address indexed user, address indexed lender, bytes32 indexed loanId, address closer, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event CloseWithSwap( address indexed user, address indexed lender, bytes32 indexed loanId, address collateralToken, address loanToken, address closer, uint256 positionCloseSize, uint256 loanCloseAmount, uint256 exitPrice, // one unit of collateralToken, denominated in loanToken uint256 currentLeverage ); event Liquidate( address indexed user, address indexed liquidator, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 repayAmount, uint256 collateralWithdrawAmount, uint256 collateralToLoanRate, uint256 currentMargin ); event Rollover( address indexed user, address indexed caller, bytes32 indexed loanId, address lender, address loanToken, address collateralToken, uint256 collateralAmountUsed, uint256 interestAmountAdded, uint256 loanEndTimestamp, uint256 gasRebate ); } contract LoanClosingsBase is State, LoanClosingsEvents, VaultController, InterestUser, GasTokenUser, SwapsUser, LiquidationHelper { enum CloseTypes { Deposit, Swap, Liquidation } function _liquidate( bytes32 loanId, address receiver, uint256 closeAmount) internal returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; (uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).getCurrentMargin( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ); require( currentMargin <= loanParamsLocal.maintenanceMargin, "healthy position" ); loanCloseAmount = closeAmount; (uint256 maxLiquidatable, uint256 maxSeizable) = _getLiquidationAmounts( loanLocal.principal, loanLocal.collateral, currentMargin, loanParamsLocal.maintenanceMargin, collateralToLoanRate, liquidationIncentivePercent[loanParamsLocal.loanToken][loanParamsLocal.collateralToken] ); if (loanCloseAmount < maxLiquidatable) { seizedAmount = maxSeizable .mul(loanCloseAmount) .div(maxLiquidatable); } else { if (loanCloseAmount > maxLiquidatable) { // adjust down the close amount to the max loanCloseAmount = maxLiquidatable; } seizedAmount = maxSeizable; } require(loanCloseAmount != 0, "nothing to liquidate"); // liquidator deposits the principal being closed _returnPrincipalWithDeposit( loanParamsLocal.loanToken, address(this), loanCloseAmount ); // a portion of the principal is repaid to the lender out of interest refunded uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, loanLocal.borrower ); if (loanCloseAmount > loanCloseAmountLessInterest) { // full interest refund goes to the borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, loanCloseAmount - loanCloseAmountLessInterest ); } if (loanCloseAmountLessInterest != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } seizedToken = loanParamsLocal.collateralToken; if (seizedAmount != 0) { loanLocal.collateral = loanLocal.collateral .sub(seizedAmount); _withdrawAsset( seizedToken, receiver, seizedAmount ); } _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, seizedAmount, collateralToLoanRate, 0, // collateralToLoanSwapRate currentMargin, CloseTypes.Liquidation ); _closeLoan( loanLocal, loanCloseAmount ); } function _rollover( bytes32 loanId, uint256 startingGas, bytes memory loanDataBytes) internal { Loan memory loanLocal = loans[loanId]; require(loanLocal.active, "loan is closed"); require( block.timestamp > loanLocal.endTimestamp.sub(1 hours), "healthy position" ); require( loanPoolToUnderlying[loanLocal.lender] != address(0), "invalid lender" ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, block.timestamp ); // Handle back interest: calculates interest owned since the loan endtime passed but the loan remained open uint256 backInterestTime; uint256 backInterestOwed; if (block.timestamp > loanLocal.endTimestamp) { backInterestTime = block.timestamp .sub(loanLocal.endTimestamp); backInterestOwed = backInterestTime .mul(loanInterestLocal.owedPerDay); backInterestOwed = backInterestOwed .div(24 hours); } uint256 maxDuration = loanParamsLocal.maxLoanTerm; if (maxDuration != 0) { // fixed-term loan, so need to query iToken for latest variable rate uint256 owedPerDay = loanLocal.principal .mul(ILoanPool(loanLocal.lender).borrowInterestRate()) .div(DAYS_IN_A_YEAR * WEI_PERCENT_PRECISION); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .add(owedPerDay); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(loanInterestLocal.owedPerDay); loanInterestLocal.owedPerDay = owedPerDay; } else { // loanInterestLocal.owedPerDay doesn't change maxDuration = ONE_MONTH; } if (backInterestTime >= maxDuration) { maxDuration = backInterestTime .add(24 hours); // adds an extra 24 hours } // update loan end time loanLocal.endTimestamp = loanLocal.endTimestamp .add(maxDuration); uint256 interestAmountRequired = loanLocal.endTimestamp .sub(block.timestamp); interestAmountRequired = interestAmountRequired .mul(loanInterestLocal.owedPerDay); interestAmountRequired = interestAmountRequired .div(24 hours); loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .add(interestAmountRequired); lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal .add(interestAmountRequired); // add backInterestOwed interestAmountRequired = interestAmountRequired .add(backInterestOwed); // collect interest (,uint256 sourceTokenAmountUsed,) = _doCollateralSwap( loanLocal, loanParamsLocal, loanLocal.collateral, interestAmountRequired, true, // returnTokenIsCollateral loanDataBytes ); loanLocal.collateral = loanLocal.collateral .sub(sourceTokenAmountUsed); if (backInterestOwed != 0) { // pay out backInterestOwed _payInterestTransfer( loanLocal.lender, loanParamsLocal.loanToken, backInterestOwed ); } uint256 gasRebate = _getRebate( loanLocal, loanParamsLocal, startingGas ); if (gasRebate != 0) { // pay out gas rebate to caller // the preceeding logic should ensure gasRebate <= collateral, but just in case, will use SafeMath here loanLocal.collateral = loanLocal.collateral .sub(gasRebate, "gasRebate too high"); _withdrawAsset( loanParamsLocal.collateralToken, msg.sender, gasRebate ); } _rolloverEvent( loanLocal, loanParamsLocal, sourceTokenAmountUsed, interestAmountRequired, gasRebate ); loans[loanId] = loanLocal; } function _closeWithDeposit( bytes32 loanId, address receiver, uint256 depositAmount) // denominated in loanToken internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(depositAmount != 0, "depositAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; // can't close more than the full principal loanCloseAmount = depositAmount > loanLocal.principal ? loanLocal.principal : depositAmount; uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); if (loanCloseAmountLessInterest != 0) { _returnPrincipalWithDeposit( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (loanCloseAmount == loanLocal.principal) { withdrawAmount = loanLocal.collateral; } else { withdrawAmount = loanLocal.collateral .mul(loanCloseAmount) .div(loanLocal.principal); } withdrawToken = loanParamsLocal.collateralToken; if (withdrawAmount != 0) { loanLocal.collateral = loanLocal.collateral - withdrawAmount; // overflow not possible _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, withdrawAmount, // collateralCloseAmount 0, // collateralToLoanSwapRate CloseTypes.Deposit ); } function _closeWithSwap( bytes32 loanId, address receiver, uint256 swapAmount, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { require(swapAmount != 0, "swapAmount == 0"); Loan memory loanLocal = loans[loanId]; _checkAuthorized( loanLocal.id, loanLocal.active, loanLocal.borrower ); LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId]; if (swapAmount > loanLocal.collateral) { swapAmount = loanLocal.collateral; } loanCloseAmount = loanLocal.principal; if (swapAmount != loanLocal.collateral) { loanCloseAmount = loanCloseAmount .mul(swapAmount) .div(loanLocal.collateral); } require(loanCloseAmount != 0, "loanCloseAmount == 0"); uint256 loanCloseAmountLessInterest = _settleInterestToPrincipal( loanLocal, loanParamsLocal, loanCloseAmount, receiver ); uint256 usedCollateral; uint256 collateralToLoanSwapRate; (usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _coverPrincipalWithSwap( loanLocal, loanParamsLocal, swapAmount, loanCloseAmountLessInterest, returnTokenIsCollateral, loanDataBytes ); if (loanCloseAmountLessInterest != 0) { // Repays principal to lender // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, loanCloseAmountLessInterest ); } if (usedCollateral != 0) { loanLocal.collateral = loanLocal.collateral .sub(usedCollateral); } withdrawToken = returnTokenIsCollateral ? loanParamsLocal.collateralToken : loanParamsLocal.loanToken; if (withdrawAmount != 0) { _withdrawAsset( withdrawToken, receiver, withdrawAmount ); } _finalizeClose( loanLocal, loanParamsLocal, loanCloseAmount, usedCollateral, collateralToLoanSwapRate, CloseTypes.Swap ); } function _checkAuthorized( bytes32 _id, bool _active, address _borrower) internal view { require(_active, "loan is closed"); require( msg.sender == _borrower || delegatedManagers[_id][msg.sender], "unauthorized" ); } function _settleInterestToPrincipal( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, address receiver) internal returns (uint256) { uint256 loanCloseAmountLessInterest = loanCloseAmount; uint256 interestRefundToBorrower = _settleInterest( loanParamsLocal, loanLocal, loanCloseAmountLessInterest ); uint256 interestAppliedToPrincipal; if (loanCloseAmountLessInterest >= interestRefundToBorrower) { // apply all of borrower interest refund torwards principal interestAppliedToPrincipal = interestRefundToBorrower; // principal needed is reduced by this amount loanCloseAmountLessInterest -= interestRefundToBorrower; // no interest refund remaining interestRefundToBorrower = 0; } else { // principal fully covered by excess interest interestAppliedToPrincipal = loanCloseAmountLessInterest; // amount refunded is reduced by this amount interestRefundToBorrower -= loanCloseAmountLessInterest; // principal fully covered by excess interest loanCloseAmountLessInterest = 0; // refund overage _withdrawAsset( loanParamsLocal.loanToken, receiver, interestRefundToBorrower ); } if (interestAppliedToPrincipal != 0) { // The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than // use the _withdrawAsset helper function vaultWithdraw( loanParamsLocal.loanToken, loanLocal.lender, interestAppliedToPrincipal ); } return loanCloseAmountLessInterest; } // The receiver always gets back an ERC20 (even WETH) function _returnPrincipalWithDeposit( address loanToken, address receiver, uint256 principalNeeded) internal { if (principalNeeded != 0) { if (msg.value == 0) { vaultTransfer( loanToken, msg.sender, receiver, principalNeeded ); } else { require(loanToken == address(wethToken), "wrong asset sent"); require(msg.value >= principalNeeded, "not enough ether"); wethToken.deposit.value(principalNeeded)(); if (receiver != address(this)) { vaultTransfer( loanToken, address(this), receiver, principalNeeded ); } if (msg.value > principalNeeded) { // refund overage Address.sendValue( msg.sender, msg.value - principalNeeded ); } } } else { require(msg.value == 0, "wrong asset sent"); } } function _coverPrincipalWithSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate) { uint256 destTokenAmountReceived; uint256 sourceTokenAmountUsed; (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _doCollateralSwap( loanLocal, loanParamsLocal, swapAmount, principalNeeded, returnTokenIsCollateral, loanDataBytes ); if (returnTokenIsCollateral) { if (destTokenAmountReceived > principalNeeded) { // better fill than expected, so send excess to borrower _withdrawAsset( loanParamsLocal.loanToken, loanLocal.borrower, destTokenAmountReceived - principalNeeded ); } withdrawAmount = swapAmount > sourceTokenAmountUsed ? swapAmount - sourceTokenAmountUsed : 0; } else { require(sourceTokenAmountUsed == swapAmount, "swap error"); withdrawAmount = destTokenAmountReceived - principalNeeded; } usedCollateral = sourceTokenAmountUsed > swapAmount ? sourceTokenAmountUsed : swapAmount; } function _doCollateralSwap( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 swapAmount, uint256 principalNeeded, bool returnTokenIsCollateral, bytes memory loanDataBytes) internal returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate) { (destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _loanSwap( loanLocal.id, loanParamsLocal.collateralToken, loanParamsLocal.loanToken, loanLocal.borrower, swapAmount, // minSourceTokenAmount loanLocal.collateral, // maxSourceTokenAmount returnTokenIsCollateral ? principalNeeded : // requiredDestTokenAmount 0, false, // bypassFee loanDataBytes ); require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount"); require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount"); } // withdraws asset to receiver function _withdrawAsset( address assetToken, address receiver, uint256 assetAmount) internal { if (assetAmount != 0) { if (assetToken == address(wethToken)) { vaultEtherWithdraw( receiver, assetAmount ); } else { vaultWithdraw( assetToken, receiver, assetAmount ); } } } function _finalizeClose( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanSwapRate, CloseTypes closeType) internal { _closeLoan( loanLocal, loanCloseAmount ); address _priceFeeds = priceFeeds; uint256 currentMargin; uint256 collateralToLoanRate; // this is still called even with full loan close to return collateralToLoanRate (bool success, bytes memory data) = _priceFeeds.staticcall( abi.encodeWithSelector( IPriceFeeds(_priceFeeds).getCurrentMargin.selector, loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral ) ); assembly { if eq(success, 1) { currentMargin := mload(add(data, 32)) collateralToLoanRate := mload(add(data, 64)) } } //// Note: We can safely skip the margin check if closing via closeWithDeposit or if closing the loan in full by any method //// require( closeType == CloseTypes.Deposit || loanLocal.principal == 0 || // loan fully closed currentMargin > loanParamsLocal.maintenanceMargin, "unhealthy position" ); _emitClosingEvents( loanParamsLocal, loanLocal, loanCloseAmount, collateralCloseAmount, collateralToLoanRate, collateralToLoanSwapRate, currentMargin, closeType ); } function _closeLoan( Loan memory loanLocal, uint256 loanCloseAmount) internal returns (uint256) { require(loanCloseAmount != 0, "nothing to close"); if (loanCloseAmount == loanLocal.principal) { loanLocal.principal = 0; loanLocal.active = false; loanLocal.endTimestamp = block.timestamp; loanLocal.pendingTradesId = 0; activeLoansSet.removeBytes32(loanLocal.id); lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id); borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id); } else { loanLocal.principal = loanLocal.principal .sub(loanCloseAmount); } loans[loanLocal.id] = loanLocal; } function _settleInterest( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 closePrincipal) internal returns (uint256) { // pay outstanding interest to lender _payInterest( loanLocal.lender, loanParamsLocal.loanToken ); LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id]; LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken]; uint256 interestTime = block.timestamp; if (interestTime > loanLocal.endTimestamp) { interestTime = loanLocal.endTimestamp; } _settleFeeRewardForInterestExpense( loanInterestLocal, loanLocal.id, loanParamsLocal.loanToken, loanLocal.borrower, interestTime ); uint256 owedPerDayRefund; if (closePrincipal < loanLocal.principal) { owedPerDayRefund = loanInterestLocal.owedPerDay .mul(closePrincipal) .div(loanLocal.principal); } else { owedPerDayRefund = loanInterestLocal.owedPerDay; } // update stored owedPerDay loanInterestLocal.owedPerDay = loanInterestLocal.owedPerDay .sub(owedPerDayRefund); lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay .sub(owedPerDayRefund); // update borrower interest uint256 interestRefundToBorrower = loanLocal.endTimestamp .sub(interestTime); interestRefundToBorrower = interestRefundToBorrower .mul(owedPerDayRefund); interestRefundToBorrower = interestRefundToBorrower .div(24 hours); if (closePrincipal < loanLocal.principal) { loanInterestLocal.depositTotal = loanInterestLocal.depositTotal .sub(interestRefundToBorrower); } else { loanInterestLocal.depositTotal = 0; } // update remaining lender interest values lenderInterestLocal.principalTotal = lenderInterestLocal.principalTotal .sub(closePrincipal); uint256 owedTotal = lenderInterestLocal.owedTotal; lenderInterestLocal.owedTotal = owedTotal > interestRefundToBorrower ? owedTotal - interestRefundToBorrower : 0; return interestRefundToBorrower; } function _getRebate( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 startingGas) internal returns (uint256 gasRebate) { // the amount of collateral drop needed to reach the maintenanceMargin level of the loan uint256 maxDrawdown = IPriceFeeds(priceFeeds).getMaxDrawdown( loanParamsLocal.loanToken, loanParamsLocal.collateralToken, loanLocal.principal, loanLocal.collateral, loanParamsLocal.maintenanceMargin ); require(maxDrawdown != 0, "unhealthy position"); // gets the gas rebate denominated in collateralToken gasRebate = SafeMath.mul( IPriceFeeds(priceFeeds).getFastGasPrice(loanParamsLocal.collateralToken) * 2, _gasUsed(startingGas) ); // ensures the gas rebate will not drop the current margin below the maintenance level gasRebate = gasRebate .min256(maxDrawdown); } function _rolloverEvent( Loan memory loanLocal, LoanParams memory loanParamsLocal, uint256 sourceTokenAmountUsed, uint256 interestAmountRequired, uint256 gasRebate) internal { emit Rollover( loanLocal.borrower, // user (borrower) msg.sender, // caller loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken sourceTokenAmountUsed, // collateralAmountUsed interestAmountRequired, // interestAmountAdded loanLocal.endTimestamp, // loanEndTimestamp gasRebate // gasRebate ); } function _emitClosingEvents( LoanParams memory loanParamsLocal, Loan memory loanLocal, uint256 loanCloseAmount, uint256 collateralCloseAmount, uint256 collateralToLoanRate, uint256 collateralToLoanSwapRate, uint256 currentMargin, CloseTypes closeType) internal { if (closeType == CloseTypes.Deposit) { emit CloseWithDeposit( loanLocal.borrower, // user (borrower) loanLocal.lender, // lender loanLocal.id, // loanId msg.sender, // closer loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } else if (closeType == CloseTypes.Swap) { // exitPrice = 1 / collateralToLoanSwapRate if (collateralToLoanSwapRate != 0) { collateralToLoanSwapRate = SafeMath.div(WEI_PRECISION * WEI_PRECISION, collateralToLoanSwapRate); } // currentLeverage = 100 / currentMargin if (currentMargin != 0) { currentMargin = SafeMath.div(10**38, currentMargin); } emit CloseWithSwap( loanLocal.borrower, // user (trader) loanLocal.lender, // lender loanLocal.id, // loanId loanParamsLocal.collateralToken, // collateralToken loanParamsLocal.loanToken, // loanToken msg.sender, // closer collateralCloseAmount, // positionCloseSize loanCloseAmount, // loanCloseAmount collateralToLoanSwapRate, // exitPrice (1 / collateralToLoanSwapRate) currentMargin // currentLeverage ); } else { // closeType == CloseTypes.Liquidation emit Liquidate( loanLocal.borrower, // user (borrower) msg.sender, // liquidator loanLocal.id, // loanId loanLocal.lender, // lender loanParamsLocal.loanToken, // loanToken loanParamsLocal.collateralToken, // collateralToken loanCloseAmount, // loanCloseAmount collateralCloseAmount, // collateralCloseAmount collateralToLoanRate, // collateralToLoanRate currentMargin // currentMargin ); } } } contract LoanClosingsWithGasToken is LoanClosingsBase { function initialize( address target) external onlyOwner { _setTarget(this.liquidateWithGasToken.selector, target); _setTarget(this.rolloverWithGasToken.selector, target); _setTarget(this.closeWithDepositWithGasToken.selector, target); _setTarget(this.closeWithSwapWithGasToken.selector, target); } function liquidateWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 closeAmount) // denominated in loanToken external payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 seizedAmount, address seizedToken ) { return _liquidate( loanId, receiver, closeAmount ); } function rolloverWithGasToken( bytes32 loanId, address gasTokenUser, bytes calldata /*loanDataBytes*/) // for future use external usesGasToken(gasTokenUser) nonReentrant { uint256 startingGas = 21000 + gasleft() + 16 * msg.data.length; // restrict to EOAs to prevent griefing attacks, during interest rate recalculation require(msg.sender == tx.origin, "only EOAs can call"); return _rollover( loanId, startingGas, "" // loanDataBytes ); } function closeWithDepositWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 depositAmount) // denominated in loanToken public payable usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithDeposit( loanId, receiver, depositAmount ); } function closeWithSwapWithGasToken( bytes32 loanId, address receiver, address gasTokenUser, uint256 swapAmount, // denominated in collateralToken bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken bytes memory /*loanDataBytes*/) // for future use public usesGasToken(gasTokenUser) nonReentrant returns ( uint256 loanCloseAmount, uint256 withdrawAmount, address withdrawToken ) { return _closeWithSwap( loanId, receiver, swapAmount, returnTokenIsCollateral, "" // loanDataBytes ); } }
* @title Helps contracts guard against reentrancy attacks. @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> @dev If you mark a function `nonReentrant`, you should also mark it `external`./
contract ReentrancyGuard { uint256 internal constant REENTRANCY_GUARD_FREE = 1; uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } }
382,112
[ 1, 44, 292, 1121, 20092, 11026, 5314, 283, 8230, 12514, 28444, 18, 225, 2663, 2894, 605, 383, 351, 275, 411, 2764, 2894, 36, 22, 144, 227, 18, 832, 20401, 512, 275, 8906, 411, 287, 338, 402, 36, 14860, 3890, 18, 1594, 34, 225, 971, 1846, 2267, 279, 445, 1375, 5836, 426, 8230, 970, 9191, 1846, 1410, 2546, 2267, 518, 1375, 9375, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 868, 8230, 12514, 16709, 288, 203, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 273, 404, 31, 203, 203, 565, 2254, 5034, 2713, 5381, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 6589, 2056, 273, 576, 31, 203, 203, 565, 2254, 5034, 2713, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 31, 203, 203, 565, 9606, 1661, 426, 8230, 970, 1435, 288, 203, 3639, 2583, 12, 2842, 313, 12514, 2531, 422, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 16, 315, 5836, 426, 8230, 970, 8863, 203, 3639, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 6589, 2056, 31, 203, 3639, 389, 31, 203, 3639, 283, 8230, 12514, 2531, 273, 2438, 2222, 54, 1258, 16068, 67, 30673, 8085, 67, 28104, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.9; //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //::::::::::: @#::::::::::: @#:::::::::::: #@j::::::::::::::::::::::::: //::::::::::: ##::::::::::: @#:::::::::::: #@j::::::::::::::::::::::::: //::::::::::: ##::::::::::: @#:::::::::::: #@j::::::::::::::::::::::::: //::::: ########: ##:: ##:: DUTCh>: ihD%y: #@Whdqy::::::::::::::::::::: //::: ###... ###: ##:: ##:: @B... @@7...t: N@N.. R@K::::::::::::::::::: //::: ##::::: ##: ##:: ##:: @Q::: @Q.::::: N@j:: z@Q::::::::::::::::::: //:::: ##DuTCH##: .@QQ@@#:: hQQQh <R@QN@Q: N@j:: z@Q::::::::::::::::::: //::::::.......: =Q@y....:::....:::......::...:::...::::::::::::::::::: //:::::::::::::: h@W? sWAP@! 'DW;:::::: KK. ydSWAP@t: NNKNQBdt::::::::: //:::::::::::::: 'zqRqj*. L@R h@w: QQ: L@5 Q@... d@@: @@U... @Q:::::::: //:::::::::::::::::...... Q@^ ^@@N@wt@BQ@ <@Q^::: @@: @@}::: @@:::::::: //:::::::::::::::::: U@@QKt... D@@L.. B@Q.. KDUTCH@Q: @@QQ#QQq::::::::: //:::::::::::::::::::.....::::::...:::...::::.......: @@!.....::::::::: //::::::::::::::::::::::::::::::::::::::::::::::::::: @@!:::::::::::::: //::::::::::::::::::::::::::::::::::::::::::::::::::: @@!:::::::::::::: //::::::::::::::01101100:01101111:01101111:01101011:::::::::::::::::::: //:::::01100100:01100101:01100101:01110000:01111001:01110010::::::::::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // // DutchSwap Auction V1.3 // Copyright (c) 2020 DutchSwap.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. // If not, see <https://github.com/deepyr/DutchSwap/>. // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // Authors: // * Adrian Guerrera / Deepyr Pty Ltd // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0-or-later // --------------------------------------------------------------------- /** * @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; } function max(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a <= b ? a : b; } } contract DutchSwapAuction { using SafeMath for uint256; /// @dev The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 public startDate; uint256 public endDate; uint256 public startPrice; uint256 public minimumPrice; uint256 public totalTokens; // Amount to be sold uint256 public priceDrop; // Price reduction from startPrice at endDate uint256 public commitmentsTotal; uint256 public tokenWithdrawn; // the amount of auction tokens already withdrawn bool private initialised; // AG: should be private bool public finalised; uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; address public auctionToken; address public paymentCurrency; address payable public wallet; // Where the auction funds will get paid mapping(address => uint256) public commitments; mapping(address => uint256) public claimed; event AddedCommitment(address addr, uint256 commitment, uint256 price); /// @dev Prevents a contract from calling itself, directly or indirectly. /// @dev https://eips.ethereum.org/EIPS/eip-2200) modifier nonReentrant() { require(_status != _ENTERED); // ReentrancyGuard: reentrant call _status = _ENTERED; _; _status = _NOT_ENTERED; } /// @dev Init function function initDutchAuction( address _funder, address _token, uint256 _totalTokens, uint256 _startDate, uint256 _endDate, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address payable _wallet ) external { require(!initialised); // Already Initialised require(_endDate > _startDate); // End date earlier than start date // Try and refactor to remove these requirements // require(_startPrice > _minimumPrice); // Starting price lower than minimum price require(_minimumPrice > 0); // Minimum price must be greater than 0 auctionToken = _token; paymentCurrency = _paymentCurrency; totalTokens = _totalTokens; startDate = _startDate; endDate = _endDate; startPrice = _startPrice; minimumPrice = _minimumPrice; wallet = _wallet; _status = _NOT_ENTERED; uint256 numerator = startPrice.sub(minimumPrice); uint256 denominator = endDate.sub(startDate); priceDrop = numerator.div(denominator); // There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 _safeTransferFrom(auctionToken, _funder, _totalTokens); initialised = true; } // Dutch Auction Price Function // ============================ // // Start Price ----- // \ // \ // \ // \ ------------ Clearing Price // / \ = AmountRaised/TokenSupply // Token Price -- \ // / \ // -- ----------- Minimum Price // Amount raised / End Time // /// @notice The average price of each token from all commitments. function tokenPrice() public view returns (uint256) { return commitmentsTotal.mul(1e18).div(totalTokens); } /// @notice Returns price during the auction function priceFunction() public view returns (uint256) { /// @dev Return Auction Price if (block.timestamp <= startDate) { return startPrice; } if (block.timestamp >= endDate) { return minimumPrice; } return _currentPrice(); } /// @notice The current clearing price of the Dutch auction function clearingPrice() public view returns (uint256) { /// @dev If auction successful, return tokenPrice if (tokenPrice() > priceFunction()) { return tokenPrice(); } return priceFunction(); } /// @notice How many tokens the user is able to claim function tokensClaimable(address _user) public view returns (uint256) { uint256 tokensAvailable = commitments[_user].mul(1e18).div(clearingPrice()); return tokensAvailable.sub(claimed[msg.sender]); } /// @notice Total amount of tokens committed at current auction price function totalTokensCommitted() public view returns(uint256) { return commitmentsTotal.mul(1e18).div(clearingPrice()); } /// @notice Total amount of tokens remaining function tokensRemaining() public view returns (uint256) { uint256 totalCommitted = totalTokensCommitted(); if (totalCommitted >= totalTokens ) { return 0; } else { return totalTokens.sub(totalCommitted); } } /// @notice Returns price during the auction function _currentPrice() private view returns (uint256) { uint256 elapsed = block.timestamp.sub(startDate); uint256 priceDiff = elapsed.mul(priceDrop); return startPrice.sub(priceDiff); } //-------------------------------------------------------- // Commit to buying tokens! //-------------------------------------------------------- /// @notice Buy Tokens by committing ETH to this contract address /// @dev Needs extra gas limit for additional state changes receive () external payable { commitEthFrom(msg.sender); } /// @dev Needs extra gas limit for additional state changes function commitEth() public payable { commitEthFrom(msg.sender); } /// @notice Commit ETH to buy tokens for any address function commitEthFrom (address payable _from) public payable { require(!finalised); // Auction was cancelled require(address(paymentCurrency) == ETH_ADDRESS); // Payment currency is not ETH // Get ETH able to be committed uint256 ethToTransfer = calculateCommitment( msg.value); // Accept ETH Payments uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { _addCommitment(_from, ethToTransfer); } // Return any ETH to be refunded if (ethToRefund > 0) { _from.transfer(ethToRefund); } } /// @notice Commit approved ERC20 tokens to buy tokens on sale function commitTokens(uint256 _amount) public { commitTokensFrom(msg.sender, _amount); } /// @dev Users must approve contract prior to committing tokens to auction function commitTokensFrom(address _from, uint256 _amount) public nonReentrant { require(!finalised); // Auction was cancelled require(address(paymentCurrency) != ETH_ADDRESS); // Only token transfers uint256 tokensToTransfer = calculateCommitment( _amount); if (tokensToTransfer > 0) { _safeTransferFrom(paymentCurrency, _from, tokensToTransfer); _addCommitment(_from, tokensToTransfer); } } /// @notice Returns the amout able to be committed during an auction function calculateCommitment( uint256 _commitment) public view returns (uint256 committed) { uint256 maxCommitment = totalTokens.mul(clearingPrice()).div(1e18); if (commitmentsTotal.add(_commitment) > maxCommitment) { return maxCommitment.sub(commitmentsTotal); } return _commitment; } /// @notice Commits to an amount during an auction function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= startDate && block.timestamp <= endDate); // Outside auction hours commitments[_addr] = commitments[_addr].add(_commitment); commitmentsTotal = commitmentsTotal.add(_commitment); emit AddedCommitment(_addr, _commitment, _currentPrice()); } //-------------------------------------------------------- // Finalise Auction //-------------------------------------------------------- /// @notice Successful if tokens sold equals totalTokens function auctionSuccessful() public view returns (bool){ return tokenPrice() >= clearingPrice(); } /// @notice Returns bool if successful or time has ended /// @dev able to claim early if auction is successful function auctionEnded() public view returns (bool){ return auctionSuccessful() || block.timestamp > endDate; } /// @notice Auction finishes successfully above the reserve /// @dev Transfer contract funds to initialised wallet. function finaliseAuction () public nonReentrant { require(!finalised); // Auction already finalised if( auctionSuccessful() ) { /// @dev Successful auction /// @dev Transfer contributed tokens to wallet. _tokenPayment(paymentCurrency, wallet, commitmentsTotal); } else if ( commitmentsTotal == 0 ) { /// @dev Cancelled Auction /// @dev You can cancel the auction before it starts require(block.timestamp <= startDate ); // Auction already started _tokenPayment(auctionToken, wallet, totalTokens); } else { /// @dev Failed auction /// @dev Return auction tokens back to wallet. require(block.timestamp > endDate ); // Auction not yet finished _tokenPayment(auctionToken, wallet, totalTokens); } finalised = true; } /// @notice Withdraw your tokens once the Auction has ended. function withdrawTokens() public nonReentrant { if( auctionSuccessful() ) { /// @dev Successful auction! Transfer claimed tokens. /// @dev AG: Could be only > min to allow early withdraw uint256 tokensToClaim = tokensClaimable(msg.sender); require(tokensToClaim > 0 ); // No tokens to claim claimed[ msg.sender] = claimed[ msg.sender].add(tokensToClaim); tokenWithdrawn = tokenWithdrawn.add(tokensToClaim); _tokenPayment(auctionToken, msg.sender, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > endDate); // Auction not yet finished uint256 fundsCommitted = commitments[ msg.sender]; require(fundsCommitted > 0); // No funds committed commitments[msg.sender] = 0; // Stop multiple withdrawals and free some gas _tokenPayment(paymentCurrency, msg.sender, fundsCommitted); } } //-------------------------------------------------------- // Helper Functions //-------------------------------------------------------- // There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 // I'm trying to make it a habit to put external calls last (reentrancy) // You can put this in an internal function if you like. function _safeTransfer(address token, address to, uint256 amount) internal { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom(address token, address from, uint256 amount) internal { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment(address _token, address payable _to, uint256 _amount) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } } }
@notice Successful if tokens sold equals totalTokens
function auctionSuccessful() public view returns (bool){ return tokenPrice() >= clearingPrice(); }
79,577
[ 1, 14277, 309, 2430, 272, 1673, 1606, 2078, 5157, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 279, 4062, 14277, 1435, 1071, 1476, 1135, 261, 6430, 15329, 203, 3639, 327, 1147, 5147, 1435, 1545, 29820, 5147, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./AntsToken.sol"; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to AntsSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // AntsSwap must mint EXACTLY the same amount of AntsSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterChef is the master of Ants. He can make Ants and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once ANTS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 lockBlock; // lockBlock uint256 lockedAmount; // lockedAmount uint256 pending; // pending amount, convert to amount via withdraw // // We do some fancy math here. Basically, any point in time, the amount of ANTSs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAntsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAntsPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. bool isSingle; // sigle token mint uint256 allocPoint; // How many allocation points assigned to this pool. ANTSs to distribute per block. uint256 lastRewardBlock; // Last block number that ANTSs distribution occurs. uint256 accAntsPerShare; // Accumulated ANTSs per share, times 1e12. See below. } // The ANTS TOKEN! AntsToken public ants; // Dev address. address public devaddr; // Block number when bonus ANTS period ends. uint256 public bonusEndBlock; // Token locked block length uint256 public halvedBlock; uint256 public halvedBlockLength = 2_000_000; // Token locked block length uint256 public antsLockedBlock; // ANTS tokens created per block. uint256 public antsPerBlock; // Bonus muliplier for early ants makers. uint256 public constant BONUS_MULTIPLIER = 5; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Invite user mapping (address => uint256) public balanceInvite; mapping (address => address) public userInvite; mapping (address => bool) public userInviteAble; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when ANTS mining starts. uint256 public startBlock; event Invite(address indexed inviter, address indexed invitee); event InviteReward(address indexed inviter, address indexed invitee, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( AntsToken _ants, address _devaddr, uint256 _antsPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { ants = _ants; devaddr = _devaddr; antsPerBlock = _antsPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; halvedBlock = _startBlock; antsLockedBlock = 200_000; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken , bool _isSingle, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, isSingle: _isSingle, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAntsPerShare: 0 })); } // Update the given pool's ANTS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending ANTSs on frontend. function pendingAnts(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAntsPerShare = pool.accAntsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt); } // View function to see pending ANTSs on frontend. function totalPendingAnts(uint256 _pid, address _user) external view returns (uint256 , uint256 ) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAntsPerShare = pool.accAntsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply)); } uint256 pending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt).add(user.pending); uint256 reward = 0; if(userInvite[_user] != address(0) && userInvite[_user] != address(this) ) { reward = pending.mul(1).div(20); } return (pending, reward); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // UserInfo storage dev = userInfo[_pid][devaddr]; // dev.pending = dev.pending.add(antsReward.div(20)); ants.mint(devaddr, antsReward.div(20)); ants.mint(address(this), antsReward); pool.accAntsPerShare = pool.accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; if(block.number >= halvedBlockLength.add(halvedBlock)) { halvedBlock = block.number; antsPerBlock = antsPerBlock.div(2); } } function updateLockBlock(uint256 _pid, uint256 _amount) internal { UserInfo storage user = userInfo[_pid][msg.sender]; if(user.lockBlock == 0) {// user.lockBlock = block.number; }else { // (b-a) * amountB/(amountA + amountbB) user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock); } } function setInviter(address _inviter) public { require(_inviter != address(0), "Inviter not null"); require(_inviter != msg.sender, "Inviter cannot be self"); require(userInviteAble[_inviter], "Inviter invalid"); userInvite[msg.sender] = _inviter; } function depositWithInvite(uint256 _pid, uint256 _amount, address _inviter) public { if( userInvite[msg.sender] == address(0) ) { require(_inviter != address(0), "Inviter not null"); require(_inviter != msg.sender, "Inviter cannot be self"); require(userInviteAble[_inviter], "Inviter invalid"); userInvite[msg.sender] = _inviter; emit Invite(_inviter, msg.sender); } deposit(_pid, _amount); } // Deposit LP tokens to MasterChef for ANTS allocation. function deposit(uint256 _pid, uint256 _amount) public { if(_amount > 0 && !userInviteAble[msg.sender]) { userInviteAble[msg.sender] = true; } if(userInvite[msg.sender] == address(0) ) { userInvite[msg.sender] = address(this); } updateLockBlock(_pid, _amount); updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt); // safeAntsTransfer(msg.sender, pending); user.pending = user.pending.add(pending); } if(pool.isSingle) { chefSafeTransferFrom(pool.lpToken, address(msg.sender), address(this), _amount); }else { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt); user.pending = user.pending.add(pending); //pending ++ //exec safeAntsTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12); if(pool.isSingle) { chefSafeTransfer(pool.lpToken, address(msg.sender), _amount); }else { pool.lpToken.safeTransfer(address(msg.sender), _amount); } emit Withdraw(msg.sender, _pid, _amount); } function withdrawInviteReward() public { ants.mint(msg.sender, balanceInvite[msg.sender] ); balanceInvite[msg.sender] = 0; } function withdrawToken(uint256 _pid) public { updatePool(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt); user.pending = pending.add(user.pending); user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12); bool invited = userInvite[msg.sender] != address(0) && userInvite[msg.sender] != address(this); uint256 availablePending = invited? user.pending.mul(21).div(20) : user.pending; if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock ) { availablePending = availablePending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock); } if(availablePending > 0 ){ //update lockedNumber //block.number.sub(user.lockBlock).mul(withdrawAmount).div(availablePending).add(user.lockBlock); if(invited) { //mint invitee reward ants.mint(msg.sender, availablePending.mul(1).div(21)); availablePending = availablePending.mul(20).div(21); // avaliable = avaliable * 1.05 //record inviter reward address inviter = userInvite[msg.sender]; uint256 reward = availablePending.div(10); balanceInvite[inviter] = balanceInvite[inviter].add(reward); emit InviteReward(inviter, msg.sender, reward); } safeAntsTransfer(msg.sender, availablePending); user.pending = user.pending.sub(availablePending); user.lockBlock = block.number; } if(user.amount == 0 && user.pending == 0) { user.lockBlock = 0; } } function calcuAvalible(uint256 _pid , address _user) external view returns (uint256 ) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAntsPerShare = pool.accAntsPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply)); } uint256 addPending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt); uint256 totalPending = user.pending.add(addPending); bool invited = userInvite[_user] != address(0) && userInvite[_user] != address(this) ; uint256 pending = invited? totalPending.mul(21).div(20) : totalPending; if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock) { return pending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock); }else { return pending; } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if(pool.isSingle) { chefSafeTransfer(pool.lpToken, address(msg.sender), user.amount); }else { pool.lpToken.safeTransfer(address(msg.sender), user.amount); } emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe ants transfer function, just in case if rounding error causes pool to not have enough ANTSs. function safeAntsTransfer(address _to, uint256 _amount) internal { uint256 antsBal = ants.balanceOf(address(this)); if (_amount > antsBal) { ants.transfer(_to, antsBal); } else { ants.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } function chefSafeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function chefSafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } 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"); } } }
(b-a) * amountB/(amountA + amountbB)
function updateLockBlock(uint256 _pid, uint256 _amount) internal { UserInfo storage user = userInfo[_pid][msg.sender]; user.lockBlock = block.number; user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock); }
12,614,129
[ 1, 12, 70, 17, 69, 13, 225, 3844, 38, 19, 12, 8949, 37, 397, 3844, 70, 38, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2531, 1768, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 5411, 729, 18, 739, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 729, 18, 739, 1768, 273, 225, 1203, 18, 2696, 18, 1717, 12, 1355, 18, 739, 1768, 2934, 16411, 24899, 8949, 2934, 2892, 12, 1355, 18, 8949, 18, 1289, 24899, 8949, 13, 2934, 1289, 12, 1355, 18, 739, 1768, 1769, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "../../contracts/tokens/BurnableXcert.sol"; import "../../contracts/tokens/PausableXcert.sol"; import "../../contracts/tokens/RevokableXcert.sol"; /** * @dev This is an example implementation of the Xcert smart contract with all available extensions. */ contract XcertFullMock is BurnableXcert, PausableXcert, RevokableXcert { /** * @dev Contract constructor. * @param _name A descriptive name for a collection of NFTs. * @param _symbol An abbreviated name for NFT. * @param _conventionId A bytes4 of keccak256 of json schema representing 0xcert protocol * convention. */ constructor( string _name, string _symbol, bytes4 _conventionId ) public { nftName = _name; nftSymbol = _symbol; nftConventionId = _conventionId; isPaused = false; //set the default pause state } }
* @dev This is an example implementation of the Xcert smart contract with all available extensions./
contract XcertFullMock is BurnableXcert, PausableXcert, RevokableXcert { constructor( string _name, string _symbol, bytes4 _conventionId ) public { nftName = _name; nftSymbol = _symbol; nftConventionId = _conventionId; } }
13,003,100
[ 1, 2503, 353, 392, 3454, 4471, 434, 326, 1139, 7593, 13706, 6835, 598, 777, 2319, 4418, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1139, 7593, 5080, 9865, 353, 605, 321, 429, 60, 7593, 16, 21800, 16665, 60, 7593, 16, 14477, 601, 429, 60, 7593, 288, 203, 203, 225, 3885, 12, 203, 565, 533, 389, 529, 16, 203, 565, 533, 389, 7175, 16, 203, 565, 1731, 24, 389, 591, 11111, 548, 203, 225, 262, 203, 565, 1071, 203, 225, 288, 203, 565, 290, 1222, 461, 273, 389, 529, 31, 203, 565, 290, 1222, 5335, 273, 389, 7175, 31, 203, 565, 290, 1222, 25947, 548, 273, 389, 591, 11111, 548, 31, 203, 225, 289, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA078b117B61a357465f12C1eB8c96b2CddbACb88/sources/BundleExecutor.sol
This is the function we call/
function flashLoan(uint256 _profitMul1000, address[] memory _targets, bytes[] memory _payloads) public onlyOwner { The flash loan functionality in dydx is predicated by their "operate" function, which takes a list of operations to execute, and defers validating the state of things until it's done executing them. We thus create three operations, a Withdraw (which loans us the funds), a Call (which invokes the callFunction method on this contract), and a Deposit (which repays the loan, plus the 2 wei fee), and pass them all to "operate". Note that the Deposit operation will invoke the transferFrom to pay the loan (or whatever amount it was initialised with) back to itself, there is no need to pay it back explicitly. The loan must be given as an ERC-20 token, so WETH is used instead of ETH. Other currencies (DAI, USDC) are also available, their index can be looked up by calling getMarketTokenAddress on the solo margin contract, and set as the primaryMarketId in the Withdraw and Deposit definitions. Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, }), secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); operations[1] = Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: abi.encode( _profitMul1000, _targets, _payloads ) }); operations[2] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, }), secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); Account.Info[] memory accountInfos = new Account.Info[](1); SOLO_MARGIN.operate(accountInfos, operations); }
2,949,541
[ 1, 2503, 353, 326, 445, 732, 745, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9563, 1504, 304, 12, 11890, 5034, 389, 685, 7216, 27860, 18088, 16, 1758, 8526, 3778, 389, 11358, 16, 1731, 8526, 3778, 389, 7648, 87, 13, 1071, 1338, 5541, 288, 203, 3639, 1021, 9563, 28183, 14176, 316, 7732, 13437, 353, 3479, 11780, 635, 3675, 315, 4063, 340, 6, 445, 16, 203, 3639, 1492, 5530, 279, 666, 434, 5295, 358, 1836, 16, 471, 1652, 414, 18075, 326, 919, 434, 203, 3639, 9198, 3180, 518, 1807, 2731, 11274, 2182, 18, 203, 540, 203, 3639, 1660, 12493, 752, 8925, 5295, 16, 279, 3423, 9446, 261, 12784, 437, 634, 584, 326, 284, 19156, 3631, 279, 3049, 203, 3639, 261, 12784, 18058, 326, 745, 2083, 707, 603, 333, 6835, 3631, 471, 279, 4019, 538, 305, 261, 12784, 203, 3639, 2071, 8271, 326, 28183, 16, 8737, 326, 576, 732, 77, 14036, 3631, 471, 1342, 2182, 777, 358, 315, 4063, 340, 9654, 203, 540, 203, 3639, 3609, 716, 326, 4019, 538, 305, 1674, 903, 4356, 326, 7412, 1265, 358, 8843, 326, 28183, 7010, 3639, 261, 280, 15098, 3844, 518, 1703, 30372, 598, 13, 1473, 358, 6174, 16, 1915, 353, 1158, 1608, 203, 3639, 358, 8843, 518, 1473, 8122, 18, 203, 540, 203, 3639, 1021, 28183, 1297, 506, 864, 487, 392, 4232, 39, 17, 3462, 1147, 16, 1427, 678, 1584, 44, 353, 1399, 3560, 434, 512, 2455, 18, 4673, 203, 3639, 19239, 261, 9793, 45, 16, 11836, 5528, 13, 854, 2546, 2319, 16, 3675, 770, 848, 506, 27321, 731, 635, 203, 3639, 4440, 23232, 278, 1345, 1887, 603, 326, 3704, 83, 2 ]
./full_match/1/0x2C6bD2A550Ff9dAcE0c7e71e17C0047220317021/sources/browser/CosmoDistributor.sol
Work out how many due tokens - time passed * rate per second
uint256 drawDownRate = vestedAmount[beneficiary].mul(1e18).div(timeEnd.sub(timeStart));
4,850,665
[ 1, 2421, 596, 3661, 4906, 6541, 2430, 300, 813, 2275, 225, 4993, 1534, 2205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 3724, 4164, 4727, 273, 331, 3149, 6275, 63, 70, 4009, 74, 14463, 814, 8009, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 957, 1638, 18, 1717, 12, 957, 1685, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.7.0 <0.9.0; contract Signatory { address public serviceContractAddress; event AddedSignatory(string indexed name, string indexed key); event RemovedSignatory(string indexed name, string indexed key); // Initializing service contract address in constructor constructor(){ serviceContractAddress = 0xA6Abc17819738299B3B2c1CE46d55c74f04E290C; } // Adds a signatory function addSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "addSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit AddedSignatory(name, key); result = ret; } // Removes a signatory function removeSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "removeSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit RemovedSignatory(name, key); result = ret; } // Gets signatories of account function getSignatories(string memory name) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "getSignatories(string)", name); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); result = ret; } }
Removes a signatory
function removeSignatory(string memory name, string memory key) public returns (bytes memory result) { bytes memory payload = abi.encodeWithSignature( "removeSignatory(string,string)", name, key); (bool success, bytes memory ret) = address(serviceContractAddress).delegatecall(payload); require(success, "Error calling service contract function"); emit RemovedSignatory(name, key); result = ret; }
13,122,597
[ 1, 6220, 279, 1573, 8452, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 2766, 8452, 12, 1080, 3778, 508, 16, 533, 3778, 498, 13, 1071, 1135, 261, 3890, 3778, 563, 13, 288, 203, 3639, 1731, 3778, 2385, 273, 24126, 18, 3015, 1190, 5374, 12, 203, 5411, 315, 4479, 2766, 8452, 12, 1080, 16, 1080, 2225, 16, 203, 5411, 508, 16, 203, 5411, 498, 1769, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 325, 13, 273, 1758, 12, 3278, 8924, 1887, 2934, 22216, 1991, 12, 7648, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 668, 4440, 1156, 6835, 445, 8863, 203, 3639, 3626, 2663, 9952, 2766, 8452, 12, 529, 16, 498, 1769, 203, 3639, 563, 273, 325, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.10; import "./ERC721.sol"; import "./Ownable.sol"; import "./Strings.sol"; /** __ _ / /| | __ _ _ __ ___ __ _/\ /\___ _ __ ___ ___ / / | |/ _` | '_ ` _ \ / _` \ \ / / _ \ '__/ __|/ _ \ / /__| | (_| | | | | | | (_| |\ V / __/ | \__ \ __/ \____/_|\__,_|_| |_| |_|\__,_| \_/ \___|_| |___/\___| **/ /// @title Pixelated Llama /// @author delta devs (https://twitter.com/deltadevelopers) /// @notice Thrown when attempting to mint while the dutch auction has not started yet. error AuctionNotStarted(); /// @notice Thrown when attempting to mint whilst the total supply (of either static or animated llamas) has been reached. error MintedOut(); /// @notice Thrown when the value of the transaction is not enough when attempting to purchase llama during dutch auction or minting post auction. error NotEnoughEther(); contract PixelatedLlama is ERC721, Ownable { using Strings for uint256; /*/////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////*/ uint256 public constant provenanceHash = 0x7481a3a60827a9db04e46389b14c42d8f0ba2106ed9b239db8249929a8ab9f0b; /// @notice The total supply of Llamas, consisting of both static & animated llamas. uint256 public constant totalSupply = 4000; /// @notice The total supply cap of animated llamas. uint256 public constant animatedSupplyCap = 500; /// @notice The total supply cap of static llamas. /// @dev This does not mean there are 4000 llamas, it means that 4000 is the last tokenId of a static llama. uint256 public constant staticSupplyCap = 4000; /// @notice The total supply cap of the dutch auction. /// @dev 1600 is the (phase 2) whitelist allocation. uint256 public constant auctionSupplyCap = staticSupplyCap - 1600; /// @notice The current supply of animated llamas, and a counter for the next static tokenId. uint256 public animatedSupply; /// @notice The current static supply of llamas, and a counter for the next animated tokenId. /// @dev Starts at the animated supply cap, since the first 500 tokenIds are used for the animated llama supply. uint256 public staticSupply = animatedSupplyCap; /// @notice The UNIX timestamp of the begin of the dutch auction. uint256 constant auctionStartTime = 1645628400; /// @notice The start price of the dutch auction. uint256 public auctionStartPrice = 1.14 ether; /// @notice Allocation of static llamas mintable per address. /// @dev Used for both free minters in Phase 1, and WL minters after the DA. mapping(address => uint256) public staticWhitelist; /// @notice Allocation of animated llamas mintable per address. /// @dev Not used for the WL phase, only for free mints. mapping(address => uint256) public animatedWhitelist; /// @notice The mint price of a static llama. uint256 public staticPrice; /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ /// @notice The base URI which retrieves token metadata. string baseURI; /// @notice Guarantees that the dutch auction has started. /// @dev This also warms up the storage slot for auctionStartTime to save gas in getCurrentTokenPrice modifier auctionStarted() { if (block.timestamp < auctionStartTime) revert AuctionNotStarted(); _; } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _baseURI) ERC721("Pixelated Llama", "PXLLMA") { baseURI = _baseURI; } /*/////////////////////////////////////////////////////////////// METADATA LOGIC //////////////////////////////////////////////////////////////*/ function tokenURI(uint256 id) public view override returns (string memory) { return string(abi.encodePacked(baseURI, id.toString())); } function setBaseURI(string memory _baseURI) public onlyOwner { baseURI = _baseURI; } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. function uploadStaticWhitelist( address[] calldata addresses ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = 1; } } /// @notice Uploads the number of mintable static llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of static llamas allocated to the same index in the first array. function uploadStaticWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { staticWhitelist[addresses[i]] = counts[i]; } } /// @notice Uploads the number of mintable animated llamas for each WL address. /// @param addresses The WL addresses. /// @param counts The number of animated llamas allocated to the same index in the first array. function uploadAnimatedWhitelist( address[] calldata addresses, uint256[] calldata counts ) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { animatedWhitelist[addresses[i]] = counts[i]; } } /*/////////////////////////////////////////////////////////////// DUTCH AUCTION LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Mints one static llama during the dutch auction. function mintAuction() public payable auctionStarted { if (msg.value < getCurrentTokenPrice()) revert NotEnoughEther(); if (staticSupply >= auctionSupplyCap) revert MintedOut(); unchecked { _mint(msg.sender, staticSupply); staticSupply++; } } /// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin /// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price. function validCalculatedTokenPrice() private view returns (uint256) { uint256 priceReduction = ((block.timestamp - auctionStartTime) / 5 minutes) * 0.1 ether; return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0; } /// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price. /// @return The current dutch auction price. function getCurrentTokenPrice() public view returns (uint256) { return max(validCalculatedTokenPrice(), 0.01 ether); } /// @notice Returns the price needed for a user to mint the static llamas allocated to him. function getWhitelistPrice() public view returns (uint256) { return staticPrice * staticWhitelist[msg.sender]; } /*/////////////////////////////////////////////////////////////// FREE & WL MINT LOGIC //////////////////////////////////////////////////////////////*/ /// @notice Allows the contract deployer to set the price for static llamas (after the DA). /// @param _staticPrice The new price for a static llama. function setStaticPrice(uint256 _staticPrice) public onlyOwner { staticPrice = _staticPrice; } /// @notice Mints all static llamas allocated to the sender, for use by free minters in the first phase, and WL minters post-auction. function mintStaticLlama() public payable { uint256 count = staticWhitelist[msg.sender]; if (staticSupply + count > staticSupplyCap) revert MintedOut(); if (msg.value < staticPrice * count) revert NotEnoughEther(); unchecked { delete staticWhitelist[msg.sender]; _bulkMint(msg.sender, staticSupply, count); staticSupply += count; } } /// @notice Mints all animated llamas allocated to the sender, for use by free minters in the first phase. function mintAnimatedLlama() public payable { uint256 count = animatedWhitelist[msg.sender]; if (animatedSupply + count > animatedSupplyCap) revert MintedOut(); unchecked { delete animatedWhitelist[msg.sender]; _bulkMint(msg.sender, animatedSupply, count); animatedSupply += count; } } /// @notice Mints all allocated llamas to the sender in one transaction. function bulkMint() public payable { mintAnimatedLlama(); mintStaticLlama(); } /// @notice Mints multiple llamas in bulk. /// @param to The address to transfer minted assets to. /// @param id The token ID of the first llama that will be minted. /// @param count The amount of llamas to be minted. function _bulkMint( address to, uint256 id, uint256 count ) internal { /// @dev We never mint to address(0) so this require is unnecessary. // require(to != address(0), "INVALID_RECIPIENT"); unchecked { balanceOf[to] += count; } for (uint256 i = id; i < id + count; i++) { /// @dev The following require has been removed because the tokens mint in succession and this function is no longer called post mint phase. // require(ownerOf[i] == address(0), "ALREADY_MINTED"); ownerOf[i] = to; emit Transfer(address(0), to, i); } } /// @notice Withdraws collected funds to the contract owner. function withdraw() public onlyOwner { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success); } /// @notice Permits the contract owner to roll over unminted animated llamas in case of a failed mint-out. function rollOverAnimated(address wallet) public onlyOwner { uint count = animatedSupplyCap - animatedSupply; _bulkMint(wallet, animatedSupply, count); unchecked { animatedSupply += count; } } /// @notice Permits the contract owner to roll over unminted static llamas in case of a failed mint-out. function rollOverStatic(address wallet) public onlyOwner { uint count = staticSupplyCap - staticSupply; _bulkMint(wallet, staticSupply, count); unchecked { staticSupply += count; } } /*/////////////////////////////////////////////////////////////// UTILS //////////////////////////////////////////////////////////////*/ /// @notice Returns the greater of two numbers. function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @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) public pure override(ERC721, Ownable) returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x7f5828d0; // ERC165 Interface ID for ERC173 } }
@notice Mints all static llamas allocated to the sender, for use by free minters in the first phase, and WL minters post-auction.
function mintStaticLlama() public payable { uint256 count = staticWhitelist[msg.sender]; if (staticSupply + count > staticSupplyCap) revert MintedOut(); if (msg.value < staticPrice * count) revert NotEnoughEther(); unchecked { delete staticWhitelist[msg.sender]; _bulkMint(msg.sender, staticSupply, count); staticSupply += count; } }
11,861,606
[ 1, 49, 28142, 777, 760, 6579, 301, 345, 11977, 358, 326, 5793, 16, 364, 999, 635, 4843, 1131, 5432, 316, 326, 1122, 6855, 16, 471, 678, 48, 1131, 5432, 1603, 17, 69, 4062, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 5788, 48, 80, 20789, 1435, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 1056, 273, 760, 18927, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 261, 3845, 3088, 1283, 397, 1056, 405, 760, 3088, 1283, 4664, 13, 15226, 490, 474, 329, 1182, 5621, 203, 3639, 309, 261, 3576, 18, 1132, 411, 760, 5147, 380, 1056, 13, 15226, 2288, 664, 4966, 41, 1136, 5621, 203, 203, 3639, 22893, 288, 203, 5411, 1430, 760, 18927, 63, 3576, 18, 15330, 15533, 203, 5411, 389, 14597, 49, 474, 12, 3576, 18, 15330, 16, 760, 3088, 1283, 16, 1056, 1769, 203, 5411, 760, 3088, 1283, 1011, 1056, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; contract initializable5 { //inject NONSTANDARD NAMING bool private initialized; bool private initializing; modifier INITIALIZER65() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING // 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; } contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); } function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING } function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED61(); __OWNABLE_INIT_UNCHAINED84(); } function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER78(); _owner = msgSender; emit OWNERSHIPTRANSFERRED52(address(0), msgSender); } function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER81() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED52(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED52(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } library safemath14 { //inject NONSTANDARD NAMING function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB60(a, b, "SafeMath: subtraction overflow"); } function SUB60(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 MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV54(a, b, "SafeMath: division by zero"); } function DIV54(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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD56(a, b, "SafeMath: modulo by zero"); } function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface ierc2086 { //inject NONSTANDARD NAMING function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library console87 { //inject NONSTANDARD NAMING address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address36; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG40() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log()")); } function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0)); } function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0)); } function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0)); } function LOG40(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0)); } function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } interface iuniswapv2factory11 { //inject NONSTANDARD NAMING event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING function FEETO47() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING function SETFEETO7(address) external; //inject NONSTANDARD NAMING function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING } contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING using safemath14 for uint256; function INITIALIZE58( //inject NONSTANDARD NAMING address _NANOCOREAddress, address _WETHAddress, address _uniswapFactory ) public INITIALIZER65 { ownableupgradesafe25.__OWNABLE_INIT13(); nanocoreTokenAddress = _NANOCOREAddress; WETHAddress = _WETHAddress; tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress); feePercentX100 = 15; paused = false; // We start paused until sync post LGE happens. } address tokenUniswapPair; iuniswapv2factory11 public uniswapFactory; address internal WETHAddress; address nanocoreTokenAddress; address nanocoreVaultAddress; uint8 public feePercentX100; // max 255 = 25.5% artificial clamp uint256 public lastTotalSupplyOfLPTokens; bool paused; // Pausing transfers of the token function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING paused = _pause; } function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING feePercentX100 = _feeMultiplier; } function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING nanocoreVaultAddress = _nanocoreVaultAddress; } function SYNC99() public { //inject NONSTANDARD NAMING uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING address sender, address recipient, // unusued maybe use din future uint256 amount ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { require(paused == false, "FEE APPROVER: Transfers Paused"); uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25(); // console.log("sender is " , sender); // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); // console.log("Old LP supply", lastTotalSupplyOfLPTokens); // console.log("Current LP supply", _LPSupplyOfPairTotal); if(sender == tokenUniswapPair) require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); // console.log('Sender is pair' , sender == tokenUniswapPair); // console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal); if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it) transferToFeeDistributorAmount = 0; transferToAmount = amount; } else { console87.LOG40("Normal fee transfer"); transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000); transferToAmount = amount.SUB60(transferToFeeDistributorAmount); } lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; } }
inject NONSTANDARD NAMING
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) {
1,018,811
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10025, 4848, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* || THE LEXDAO REGISTRY (TLDR) || version 0.3 DEAR MSG.SENDER(S): / TLDR is a project in beta. // Please audit and use at your own risk. /// Entry into TLDR shall not create an attorney/client relationship. //// Likewise, TLDR should not be construed as legal advice or replacement for professional counsel. ///// STEAL THIS C0D3SL4W || lexDAO || ~presented by Open, ESQ LLC_DAO~ < https://mainnet.aragon.org/#/openesquire/ > */ pragma solidity 0.5.9; /*************** OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 transactional scripts ***************/ /** * @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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ 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. * * NOTE: This is a feature of the next version of OpenZeppelin Contracts. * @dev Get it via `npm install @openzeppelin/contracts@next`. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ScribeRole is Context { using Roles for Roles.Role; event ScribeAdded(address indexed account); event ScribeRemoved(address indexed account); Roles.Role private _Scribes; constructor () internal { _addScribe(_msgSender()); } modifier onlyScribe() { require(isScribe(_msgSender()), "ScribeRole: caller does not have the Scribe role"); _; } function isScribe(address account) public view returns (bool) { return _Scribes.has(account); } function renounceScribe() public { _removeScribe(_msgSender()); } function _addScribe(address account) internal { _Scribes.add(account); emit ScribeAdded(account); } function _removeScribe(address account) internal { _Scribes.remove(account); emit ScribeRemoved(account); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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 {ERC20Mintable}. * * 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; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /*************** TLDR CONTRACT ***************/ contract TLDR is ScribeRole, ERC20 { // TLDR: Curated covenant & escrow scriptbase with incentivized arbitration using SafeMath for uint256; // lexDAO reference for lexScribe reputation governance fees (Ξ) address payable public lexDAO; // TLDR (LEX) ERC-20 token references address public tldrAddress = address(this); ERC20 tldrToken = ERC20(tldrAddress); string public name = "TLDR"; string public symbol = "LEX"; uint8 public decimals = 18; // counters for lexScribe lexScriptWrapper and registered DR (rdr) / DC (rdc) uint256 public LSW; // number of lexScriptWrapper enscribed uint256 public RDC; // number of rdc uint256 public RDR; // number of rdr // mapping for lexScribe reputation governance program mapping(address => uint256) public reputation; // mapping lexScribe reputation points mapping(address => uint256) public lastActionTimestamp; // mapping Unix timestamp of lexScribe governance actions (cooldown) mapping(address => uint256) public lastSuperActionTimestamp; // mapping Unix timestamp of material lexScribe governance actions requiring longer cooldown (icedown) // mapping for stored lexScript wrappers and registered digital retainers (DR / rdr) mapping (uint256 => lexScriptWrapper) public lexScript; // mapping registered lexScript 'wet code' templates mapping (uint256 => DC) public rdc; // mapping rdc call numbers for inspection and signature revocation mapping (uint256 => DR) public rdr; // mapping rdr call numbers for inspection and scripted payments struct lexScriptWrapper { // LSW: rdr lexScript templates maintained by lexScribes address lexScribe; // lexScribe (0x) address that enscribed lexScript template into TLDR / can make subsequent edits (lexVersion) address lexAddress; // (0x) address to receive lexScript wrapper lexFee / adjustable by associated lexScribe string templateTerms; // lexScript template terms to wrap rdr with legal security uint256 lexID; // number to reference in rdr to import lexScript terms uint256 lexVersion; // version number to mark lexScribe edits uint256 lexRate; // fixed divisible rate for lexFee in drToken per rdr payment made thereunder / e.g., 100 = 1% lexFee on rdr payDR transaction } struct DC { // Digital Covenant lexScript templates maintained by lexScribes address signatory; // DC signatory (0x) address string templateTerms; // DC templateTerms imported from referenced lexScriptWrapper string signatureDetails; // DC may include signatory name or other supplementary info uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security uint256 dcNumber; // DC number generated on signed covenant registration / identifies DC for signatory revocation uint256 timeStamp; // block.timestamp ("now") of DC registration bool revoked; // tracks signatory revocation status on DC } struct DR { // Digital Retainer created on lexScript terms maintained by lexScribes / data registered for escrow script address client; // rdr client (0x) address address provider; // provider (0x) address that receives ERC-20 payments in exchange for goods or services (deliverable) address drToken; // ERC-20 digital token (0x) address used to transfer value on Ethereum under rdr string deliverable; // description of deliverable retained for benefit of Ethereum payments uint256 lexID; // lexID number reference to include lexScriptWrapper for legal security / default '1' for generalized rdr lexScript template uint256 drNumber; // rdr number generated on DR registration / identifies rdr for payDR function calls uint256 timeStamp; // block.timestamp ("now") of registration used to calculate retainerTermination UnixTime uint256 retainerTermination; // termination date of rdr in UnixTime / locks payments to provider / after, remainder can be withrawn by client uint256 deliverableRate; // rate for rdr deliverables in wei amount / 1 = 1000000000000000000 uint256 paid; // tracking amount of designated ERC-20 digital value paid under rdr in wei amount for payCap logic uint256 payCap; // value cap limit on rdr payments in wei amount bool confirmed; // tracks client countersignature status bool disputed; // tracks dispute status from client or provider / if called, locks remainder of escrow rdr payments for reputable lexScribe resolution } constructor(string memory tldrTerms, uint256 tldrLexRate, address tldrLexAddress, address payable _lexDAO) public { // deploys TLDR contract & stores base lexScript reputation[msg.sender] = 1; // sets TLDR summoner lexScribe reputation to '1' initial value lexDAO = _lexDAO; // sets initial lexDAO (0x) address LSW = LSW.add(1); // counts initial 'tldr' entry to LSW lexScript[1] = lexScriptWrapper( // populates default '1' lexScript data for reference in LSW and rdr msg.sender, tldrLexAddress, tldrTerms, 1, 0, tldrLexRate); } // TLDR Contract Events event Enscribed(uint256 indexed lexID, uint256 indexed lexVersion, address indexed lexScribe); // triggered on successful LSW creation / edits to LSW event Signed(uint256 indexed lexID, uint256 indexed dcNumber, address indexed signatory); // triggered on successful DC creation / edits to DC event Registered(uint256 indexed drNumber, uint256 indexed lexID, address indexed provider); // triggered on successful rdr event Confirmed(uint256 indexed drNumber, uint256 indexed lexID, address indexed client); // triggered on successful rdr confirmation event Paid(uint256 indexed drNumber, uint256 indexed lexID); // triggered on successful rdr payments event Disputed(uint256 indexed drNumber); // triggered on rdr dispute event Resolved(uint256 indexed drNumber); // triggered on successful rdr dispute resolution /*************** TLDR GOVERNANCE FUNCTIONS ***************/ // restricts lexScribe TLDR reputation governance function calls to once per day (cooldown) modifier cooldown() { require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); // enforces cooldown period _; lastActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // restricts material lexScribe TLDR reputation staking and lexDAO governance function calls to once per 90 days (icedown) modifier icedown() { require(now.sub(lastSuperActionTimestamp[msg.sender]) > 90 days); // enforces icedown period _; lastSuperActionTimestamp[msg.sender] = now; // block.timestamp, "now" } // lexDAO can add new lexScribe to maintain TLDR function addScribe(address account) public { require(msg.sender == lexDAO); _addScribe(account); reputation[account] = 1; } // lexDAO can remove lexScribe from TLDR / slash reputation function removeScribe(address account) public { require(msg.sender == lexDAO); _removeScribe(account); reputation[account] = 0; } // lexDAO can update (0x) address receiving reputation governance stakes (Ξ) / maintaining lexScribe registry function updateLexDAO(address payable newLexDAO) public { require(msg.sender == lexDAO); require(newLexDAO != address(0)); // program safety check / newLexDAO cannot be "0" burn address lexDAO = newLexDAO; // updates lexDAO (0x) address } // lexScribes can submit ether (Ξ) value for TLDR reputation and special TLDR function access (TLDR write privileges, rdr dispute resolution role) function submitETHreputation() payable public onlyScribe icedown { require(msg.value == 0.1 ether); // tenth of ether (Ξ) fee for refreshing reputation in lexDAO reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer address(lexDAO).transfer(msg.value); // transfers ether value (Ξ) to designated lexDAO (0x) address } // lexScribes can burn minted LEX value for TLDR reputation function submitLEXreputation() public onlyScribe icedown { _burn(_msgSender(), 10000000000000000000); // 10 LEX burned reputation[msg.sender] = 3; // sets / refreshes lexScribe reputation to '3' max value, 'three strikes, you're out' buffer } // public check on lexScribe reputation status function isReputable(address x) public view returns (bool) { // returns true if lexScribe is reputable return reputation[x] > 0; } // reputable lexScribes can reduce reputation within cooldown period function reduceScribeRep(address reducedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != reducedLexScribe); // program governance check / cannot reduce own reputation reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); // reduces reputation by "1" } // reputable lexScribes can repair reputation within cooldown period function repairScribeRep(address repairedLexScribe) cooldown public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable require(msg.sender != repairedLexScribe); // program governance check / cannot repair own reputation require(reputation[repairedLexScribe] < 3); // program governance check / cannot repair fully reputable lexScribe require(reputation[repairedLexScribe] > 0); // program governance check / cannot repair disreputable lexScribe reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); // repairs reputation by "1" } /*************** TLDR LEXSCRIBE FUNCTIONS ***************/ // reputable lexScribes can register lexScript legal wrappers on TLDR and program ERC-20 lexFees associated with lexID / LEX mint, "1" function writeLexScript(string memory templateTerms, uint256 lexRate, address lexAddress) public { require(isReputable(msg.sender)); // program governance check / lexScribe must be reputable uint256 lexID = LSW.add(1); // reflects new lexScript value for tracking lexScript wrappers LSW = LSW.add(1); // counts new entry to LSW lexScript[lexID] = lexScriptWrapper( // populate lexScript data for rdr / rdc usage msg.sender, lexAddress, templateTerms, lexID, 0, lexRate); _mint(msg.sender, 1000000000000000000); // mints lexScribe "1" LEX for contribution to TLDR emit Enscribed(lexID, 0, msg.sender); } // lexScribes can update TLDR lexScript wrappers with new templateTerms and (0x) newLexAddress / version up LSW function editLexScript(uint256 lexID, string memory templateTerms, address lexAddress) public { lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data require(msg.sender == lS.lexScribe); // program safety check / authorization uint256 lexVersion = lS.lexVersion.add(1); // updates lexVersion lexScript[lexID] = lexScriptWrapper( // populates updated lexScript data for rdr / rdc usage msg.sender, lexAddress, templateTerms, lexID, lexVersion, lS.lexRate); emit Enscribed(lexID, lexVersion, msg.sender); } /*************** TLDR MARKET FUNCTIONS ***************/ // public can sign and associate (0x) identity with lexScript digital covenant wrapper function signDC(uint256 lexID, string memory signatureDetails) public { // sign Digital Covenant with (0x) address require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check lexScriptWrapper storage lS = lexScript[lexID]; // retrieve LSW data uint256 dcNumber = RDC.add(1); // reflects new rdc value for public inspection and signature revocation RDC = RDC.add(1); // counts new entry to RDC rdc[dcNumber] = DC( // populates rdc data msg.sender, lS.templateTerms, signatureDetails, lexID, dcNumber, now, false); emit Signed(lexID, dcNumber, msg.sender); } // registered DC signatories can revoke (0x) signature function revokeDC(uint256 dcNumber) public { // revoke Digital Covenant signature with (0x) address DC storage dc = rdc[dcNumber]; // retrieve rdc data require(msg.sender == dc.signatory); // program safety check / authorization rdc[dcNumber] = DC(// updates rdc data msg.sender, "Signature Revoked", // replaces Digital Covenant terms with revocation message dc.signatureDetails, dc.lexID, dc.dcNumber, now, // updates to revocation block.timestamp true); // reflects revocation status emit Signed(dc.lexID, dcNumber, msg.sender); } // goods and/or service providers can register DR with TLDR lexScript (lexID) function registerDR( // rdr address client, address drToken, string memory deliverable, uint256 retainerDuration, uint256 deliverableRate, uint256 payCap, uint256 lexID) public { require(lexID > (0)); // program safety check require(lexID <= LSW); // program safety check require(deliverableRate <= payCap); // program safety check / economics uint256 drNumber = RDR.add(1); // reflects new rdr value for inspection and escrow management uint256 retainerTermination = now.add(retainerDuration); // rdr termination date in UnixTime, "now" block.timestamp + retainerDuration RDR = RDR.add(1); // counts new entry to RDR rdr[drNumber] = DR( // populate rdr data client, msg.sender, drToken, deliverable, lexID, drNumber, now, // block.timestamp, "now" retainerTermination, deliverableRate, 0, payCap, false, false); emit Registered(drNumber, lexID, msg.sender); } // rdr client can confirm rdr offer script and countersign drNumber / trigger escrow deposit in approved payCap amount function confirmDR(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization dr.confirmed = true; // reflect rdr client countersignature ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transferFrom(msg.sender, address(this), dr.payCap); // escrows payCap amount in approved drToken into TLDR emit Confirmed(drNumber, dr.lexID, msg.sender); } // rdr client can call to delegate role function delegateDRclient(uint256 drNumber, address clientDelegate) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization require(dr.paid < dr.payCap); // program safety check / economics dr.client = clientDelegate; // updates rdr client address to delegate } // rdr parties can initiate dispute and lock escrowed remainder of rdr payCap in TLDR until resolution by reputable lexScribe function disputeDR(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client || msg.sender == dr.provider); // program safety check / authorization require(dr.paid < dr.payCap); // program safety check / economics dr.disputed = true; // updates rdr value to reflect dispute status, "true" emit Disputed(drNumber); } // reputable lexScribe can resolve rdr dispute with division of remaining payCap amount in wei accounting for 5% fee / LEX mint, "1" function resolveDR(uint256 drNumber, uint256 clientAward, uint256 providerAward) public { DR storage dr = rdr[drNumber]; // retrieve rdr data uint256 remainder = dr.payCap.sub(dr.paid); // alias remainder rdr wei amount for rdr resolution reference uint256 resolutionFee = remainder.div(20); // calculates 5% lexScribe dispute resolution fee require(dr.disputed == true); // program safety check / status require(clientAward.add(providerAward) == remainder.sub(resolutionFee)); // program safety check / economics require(msg.sender != dr.client); // program safety check / authorization / client cannot resolve own dispute as lexScribe require(msg.sender != dr.provider); // program safety check / authorization / provider cannot resolve own dispute as lexScribe require(isReputable(msg.sender)); // program governance check / resolving lexScribe must be reputable require(balanceOf(msg.sender) >= 5000000000000000000); // program governance check / resolving lexScribe must have at least "5" LEX balance ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transfer(dr.client, clientAward); // executes ERC-20 award transfer to rdr client drTokenERC20.transfer(dr.provider, providerAward); // executes ERC-20 award transfer to rdr provider drTokenERC20.transfer(msg.sender, resolutionFee); // executes ERC-20 fee transfer to resolving lexScribe _mint(msg.sender, 1000000000000000000); // mints resolving lexScribe "1" LEX for contribution to TLDR dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure emit Resolved(drNumber); } // client can call to pay rdr on TLDR function payDR(uint256 drNumber) public { // releases escrowed drToken deliverableRate amount to provider (0x) address / lexFee for attached lexID lexAddress DR storage dr = rdr[drNumber]; // retrieve rdr data lexScriptWrapper storage lS = lexScript[dr.lexID]; // retrieve LSW data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now <= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization require(dr.paid.add(dr.deliverableRate) <= dr.payCap); // program safety check / economics uint256 lexFee = dr.deliverableRate.div(lS.lexRate); // derives lexFee from rdr deliverableRate ERC20 drTokenERC20 = ERC20(dr.drToken); drTokenERC20.transfer(dr.provider, dr.deliverableRate.sub(lexFee)); // executes ERC-20 transfer to rdr provider in deliverableRate amount drTokenERC20.transfer(lS.lexAddress, lexFee); // executes ERC-20 transfer of lexFee to (0x) lexAddress identified in lexID dr.paid = dr.paid.add(dr.deliverableRate); // tracks total ERC-20 wei amount paid under rdr / used to calculate rdr remainder emit Paid(drNumber, dr.lexID); } // client can call to withdraw rdr remainder on TLDR after termination function withdrawRemainder(uint256 drNumber) public { DR storage dr = rdr[drNumber]; // retrieve rdr data require(dr.confirmed == true); // program safety check / status require(dr.disputed == false); // program safety check / status require(now >= dr.retainerTermination); // program safety check / time require(msg.sender == dr.client); // program safety check / authorization uint256 remainder = dr.payCap.sub(dr.paid); // derive rdr remainder ERC20 drTokenERC20 = ERC20(dr.drToken); require(remainder > 0); // program safety check / economics drTokenERC20.transfer(dr.client, remainder); // executes ERC-20 transfer to rdr client in escrow remainder amount dr.paid = dr.paid.add(remainder); // tallies remainder to paid wei amount to reflect rdr closure } }
termination date of rdr in UnixTime / locks payments to provider / after, remainder can be withrawn by client
uint256 retainerTermination;
983,142
[ 1, 9505, 367, 1509, 434, 436, 3069, 316, 9480, 950, 342, 13046, 25754, 358, 2893, 342, 1839, 16, 10022, 848, 506, 598, 1899, 82, 635, 1004, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 325, 1521, 16516, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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; } } /** * @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); } interface IBPool is IERC20 { function version() external view returns(uint); function swapExactAmountIn(address, uint, address, uint, uint) external returns (uint, uint); function swapExactAmountOut(address, uint, address, uint, uint) external returns (uint, uint); function calcInGivenOut(uint, uint, uint, uint, uint, uint) external pure returns (uint); function calcOutGivenIn(uint, uint, uint, uint, uint, uint) external pure returns (uint); function getDenormalizedWeight(address) external view returns (uint); function swapFee() external view returns (uint); function setSwapFee(uint _swapFee) external; function bind(address token, uint balance, uint denorm) external; function rebind(address token, uint balance, uint denorm) external; function finalize( uint _swapFee, uint _initPoolSupply, address[] calldata _bindTokens, uint[] calldata _bindDenorms ) external; function setPublicSwap(bool _publicSwap) external; function setController(address _controller) external; function setExchangeProxy(address _exchangeProxy) external; function getFinalTokens() external view returns (address[] memory tokens); function getTotalDenormalizedWeight() external view returns (uint); function getBalance(address token) external view returns (uint); function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function joinPoolFor(address account, uint rewardAmountOut, uint[] calldata maxAmountsIn) external; function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn) external returns (uint tokenAmountIn); function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut) external returns (uint tokenAmountOut); function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn) external returns (uint poolAmountIn); function joinswapExternAmountIn( address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function finalizeRewardFundInfo(address _rewardFund, uint _unstakingFrozenTime) external; function addRewardPool(IERC20 _rewardToken, uint256 _startBlock, uint256 _endRewardBlock, uint256 _rewardPerBlock, uint256 _lockRewardPercent, uint256 _startVestingBlock, uint256 _endVestingBlock) external; function isBound(address t) external view returns (bool); function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice); } library Babylonian { function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = uint256(1) << RESOLUTION; uint256 private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z; require(y == 0 || (z = uint256(self._x) * y) / y == uint256(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, "FixedPoint: ZERO_RECIPROCAL"); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } interface IDecimals { function decimals() external view returns (uint8); } // fixed window oracle that recomputes the average price for the entire epochPeriod once every epochPeriod // note that the price average is only guaranteed to be over at least 1 epochPeriod, but may be over a longer epochPeriod // @dev This version 2 supports querying twap with shorted period (ie 2hrs for BSDB reference price) contract OracleMultiPairV2 is Ownable { using FixedPoint for *; using SafeMath for uint256; using UQ112x112 for uint224; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant BPOOL_BONE = 10**18; uint256 public constant ORACLE_RESERVE_MINIMUM = 10000 ether; // $10,000 /* ========== STATE VARIABLES ========== */ // governance address public operator; // epoch uint256 public startTime; uint256 public lastEpochTime; uint256 public epoch; // for display only uint256 public epochPeriod; // 2-hours update uint256 public lastUpdateHour; uint256 public updatePeriod; mapping(uint256 => uint112) public epochPrice; // BPool address public mainToken; address[] public sideTokens; uint256[] public sideTokenDecimals; IBPool[] public pools; // Pool price for update in cumulative epochPeriod uint32 public blockTimestampCumulativeLast; uint public priceCumulative; // oracle uint32 public blockTimestampLast; uint256 public priceCumulativeLast; FixedPoint.uq112x112 public priceAverage; event Updated(uint256 priceCumulativeLast); /* ========== CONSTRUCTOR ========== */ constructor( address[] memory _pools, address _mainToken, address[] memory _sideTokens, uint256 _epoch, uint256 _epochPeriod, uint256 _lastEpochTime, uint256 _updatePeriod, uint256 _lastUpdateHour ) public { require(_pools.length == _sideTokens.length, "ERR_LENGTH_MISMATCH"); mainToken = _mainToken; for (uint256 i = 0; i < _pools.length; i++) { IBPool pool = IBPool(_pools[i]); require(pool.isBound(_mainToken) && pool.isBound(_sideTokens[i]), "!bound"); require(pool.getBalance(_mainToken) != 0 && pool.getBalance(_sideTokens[i]) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideTokens[i]); sideTokenDecimals.push(IDecimals(_sideTokens[i]).decimals()); } epoch = _epoch; epochPeriod = _epochPeriod; lastEpochTime = _lastEpochTime; lastUpdateHour = _lastUpdateHour; updatePeriod = _updatePeriod; operator = msg.sender; } /* ========== GOVERNANCE ========== */ function setOperator(address _operator) external onlyOperator { operator = _operator; } function setEpoch(uint256 _epoch) external onlyOperator { epoch = _epoch; } function setEpochPeriod(uint256 _epochPeriod) external onlyOperator { require(_epochPeriod >= 1 hours && _epochPeriod <= 48 hours, '_epochPeriod out of range'); epochPeriod = _epochPeriod; } function setLastUpdateHour(uint256 _lastUpdateHour) external onlyOperator { require(_lastUpdateHour % 3600 == 0, '_lastUpdateHour is not valid'); lastUpdateHour = _lastUpdateHour; } function setUpdatePeriod(uint256 _updatePeriod) external onlyOperator { require(_updatePeriod >= 1 hours && _updatePeriod <= epochPeriod, '_updatePeriod out of range'); updatePeriod = _updatePeriod; } function addPool(address _pool, address _sideToken) public onlyOperator { IBPool pool = IBPool(_pool); require(pool.isBound(mainToken) && pool.isBound(_sideToken), "!bound"); require(pool.getBalance(mainToken) != 0 && pool.getBalance(_sideToken) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideToken); sideTokenDecimals.push(IDecimals(_sideToken).decimals()); } function removePool(address _pool, address _sideToken) public onlyOperator { uint last = pools.length - 1; for (uint256 i = 0; i < pools.length; i++) { if (address(pools[i]) == _pool && sideTokens[i] == _sideToken) { pools[i] = pools[last]; sideTokens[i] = sideTokens[last]; sideTokenDecimals[i] = sideTokenDecimals[last]; pools.pop(); sideTokens.pop(); sideTokenDecimals.pop(); break; } } } /* =================== Modifier =================== */ modifier checkEpoch { uint256 _nextEpochPoint = nextEpochPoint(); require(now >= _nextEpochPoint, "OracleMultiPair: not opened yet"); _; for (;;) { lastEpochTime = _nextEpochPoint; ++epoch; _nextEpochPoint = nextEpochPoint(); if (now < _nextEpochPoint) break; } } modifier onlyOperator() { require(operator == msg.sender, "OracleMultiPair: caller is not the operator"); _; } /* ========== VIEW FUNCTIONS ========== */ function nextEpochPoint() public view returns (uint256) { return lastEpochTime.add(epochPeriod); } function nextUpdateHour() public view returns (uint256) { return lastUpdateHour.add(updatePeriod); } /* ========== MUTABLE FUNCTIONS ========== */ // update reserves and, on the first call per block, price accumulators function updateCumulative() public { uint256 _nextUpdateHour = lastUpdateHour.add(updatePeriod); if (now >= _nextUpdateHour) { uint totalMainPriceWeight; uint totalMainPoolBal; for (uint256 i = 0; i < pools.length; i++) { uint _decimalFactor = 10 ** (uint256(18).sub(sideTokenDecimals[i])); uint tokenMainPrice = pools[i].getSpotPrice(sideTokens[i], mainToken).mul(_decimalFactor); require(tokenMainPrice != 0, "!price"); uint reserveBal = pools[i].getBalance(sideTokens[i]).mul(_decimalFactor); require(reserveBal >= ORACLE_RESERVE_MINIMUM, "!min reserve"); uint tokenBal = pools[i].getBalance(mainToken); totalMainPriceWeight = totalMainPriceWeight.add(tokenMainPrice.mul(tokenBal).div(BPOOL_BONE)); totalMainPoolBal = totalMainPoolBal.add(tokenBal); } require(totalMainPriceWeight <= uint112(- 1) && totalMainPoolBal <= uint112(- 1), 'BPool: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32); uint32 timeElapsed = blockTimestamp - blockTimestampCumulativeLast; // overflow is desired if (timeElapsed > 0 && totalMainPoolBal != 0) { // * never overflows, and + overflow is desired priceCumulative += uint(UQ112x112.encode(uint112(totalMainPriceWeight)).uqdiv(uint112(totalMainPoolBal))) * timeElapsed; blockTimestampCumulativeLast = blockTimestamp; } lastUpdateHour = _nextUpdateHour; } } /** @dev Updates 1-day EMA price. */ function update() external checkEpoch { updateCumulative(); uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; // overflow is desired if (timeElapsed == 0) { // prevent divided by zero return; } // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestampCumulativeLast; epochPrice[epoch] = priceAverage.decode(); emit Updated(priceCumulative); } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view returns (uint144 amountOut) { require(token == mainToken, "OracleMultiPair: INVALID_TOKEN"); require(now.sub(blockTimestampLast) <= epochPeriod, "OracleMultiPair: Price out-of-date"); amountOut = priceAverage.mul(amountIn).decode144(); } function twap(uint256 _amountIn) external view returns (uint144) { uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; return (timeElapsed == 0) ? priceAverage.mul(_amountIn).decode144() : FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)).mul(_amountIn).decode144(); } function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator { _token.transfer(_to, _amount); } }
========== CONSTRUCTOR ========== */
) public { require(_pools.length == _sideTokens.length, "ERR_LENGTH_MISMATCH"); mainToken = _mainToken; for (uint256 i = 0; i < _pools.length; i++) { IBPool pool = IBPool(_pools[i]); require(pool.isBound(_mainToken) && pool.isBound(_sideTokens[i]), "!bound"); pools.push(pool); sideTokens.push(_sideTokens[i]); sideTokenDecimals.push(IDecimals(_sideTokens[i]).decimals()); } epoch = _epoch; epochPeriod = _epochPeriod; lastEpochTime = _lastEpochTime; lastUpdateHour = _lastUpdateHour; updatePeriod = _updatePeriod; operator = msg.sender; }
13,674,002
[ 1, 1432, 631, 3492, 13915, 916, 422, 1432, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 288, 203, 3639, 2583, 24899, 27663, 18, 2469, 422, 389, 5564, 5157, 18, 2469, 16, 315, 9712, 67, 7096, 67, 30062, 11793, 8863, 203, 203, 3639, 2774, 1345, 273, 389, 5254, 1345, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 27663, 18, 2469, 31, 277, 27245, 288, 203, 5411, 23450, 2864, 2845, 273, 23450, 2864, 24899, 27663, 63, 77, 19226, 203, 5411, 2583, 12, 6011, 18, 291, 3499, 24899, 5254, 1345, 13, 597, 2845, 18, 291, 3499, 24899, 5564, 5157, 63, 77, 65, 3631, 17528, 3653, 8863, 203, 203, 5411, 16000, 18, 6206, 12, 6011, 1769, 203, 5411, 4889, 5157, 18, 6206, 24899, 5564, 5157, 63, 77, 19226, 203, 5411, 4889, 1345, 31809, 18, 6206, 12, 734, 557, 11366, 24899, 5564, 5157, 63, 77, 65, 2934, 31734, 10663, 203, 3639, 289, 203, 203, 3639, 7632, 273, 389, 12015, 31, 203, 3639, 7632, 5027, 273, 389, 12015, 5027, 31, 203, 3639, 1142, 14638, 950, 273, 389, 2722, 14638, 950, 31, 203, 3639, 1142, 1891, 13433, 273, 389, 2722, 1891, 13433, 31, 203, 3639, 1089, 5027, 273, 389, 2725, 5027, 31, 203, 203, 3639, 3726, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.5.0; import "./Ownable.sol"; contract DataAuth is Ownable{ event NewUser( bytes32 indexed lockId ); event UserEdited( bool result ); event UserDeleted( bool result ); struct User { address userAddress; string username; string group; uint32[] databaseList; } modifier user_exists(bytes32 _lockId) { require(owns_user(_lockId), "User does not exist"); _; } mapping (bytes32 => User) users; /* Description: adds the new user and authorized group and databases NOTE: This call is done by the administrator params: _userAddress: the public address of the user _username: name of user to add to database _group: group associated with user (group association done off-chain) _databaseList: list of databases the user wants to have access to returns: lockId: abi.encode(sha256) hash of the parameters */ function createUser(address _userAddress, string memory _username, string memory _group, uint32[] memory _databaseList) public onlyOwner returns (bytes32 lockId){ //owner need to check for duplicates lockId = sha256(abi.encode( _userAddress, _username, _group, _databaseList ) ); // reject if the user already exists if(owns_user(lockId)){ revert("lockId already exists"); } users[lockId] = User( _userAddress, _username, _group, _databaseList ); emit NewUser(lockId); return (lockId); } /* Description: get the user associated with the lockId NOTE: This call can be made by both the administrator and the user params: _lockId: indexed lockId created at createUser. Referenced mapping to user return: - requester: admin address of who requested information - userPubKey: public key of the user - username: username of the user - group: group association - databaseList: authorized database list (specified in numbers) */ function getUser(bytes32 _lockId) public user_exists(_lockId) view returns (address requester, address userAddress ,string memory username, string memory group, uint32[] memory databaseList){ User storage c = users[_lockId]; return ( msg.sender, c.userAddress, c.username, c.group, c.databaseList ); } /* Description: edits user credentials and group information - If the input is 0 or null no change will be made, else make a change NOTE: This call can only be made by the administrator params: _lockId: indexed lockId created at createUser. Referenced mapping to user _username: name of user to change on database _group: group associated with user (group association done off-chain) to change _databaseList: list of databases the user wants to have access to, having no input means there should be no change returns: boolean: true if success, else reverts */ function editUser(bytes32 _lockId, string memory _username, string memory _group, uint32[] memory _databaseList) public user_exists(_lockId) onlyOwner returns (bool){ User storage c = users[_lockId]; if (keccak256(abi.encodePacked(_username)) != keccak256("null")){ c.username = _username; } if (keccak256(abi.encodePacked(_group)) != keccak256("null")){ c.group = _group; } //checks the length of the database if (_databaseList.length > 0){ c.databaseList = _databaseList; } emit UserEdited(true); return (true); } /* Description: removes user from databases and groups NOTE: This call can only be made by the administrator params: _lockId: indexed lockId created at createUser. Referenced mapping to user returns: boolean: true if success */ function deleteUser(bytes32 _lockId) public user_exists(_lockId) onlyOwner returns (bool) { //for now haven't found a way to resize and find index of the array delete users[_lockId]; emit UserDeleted(true); return (true); } /* Check if there is a lockId with id _lockId. parmas: _lockId: Id into contracts mapping. returns: boolean, true if success */ function owns_user(bytes32 _lockId) public view returns (bool exists){ exists = (users[_lockId].userAddress != address(0)); } }
/for now haven't found a way to resize and find index of the array
function deleteUser(bytes32 _lockId) public user_exists(_lockId) onlyOwner returns (bool) { delete users[_lockId]; emit UserDeleted(true); return (true); } parmas: _lockId: Id into contracts mapping. returns: boolean, true if success
12,687,284
[ 1, 19, 1884, 2037, 15032, 1404, 1392, 279, 4031, 358, 7041, 471, 1104, 770, 434, 326, 526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1430, 1299, 12, 3890, 1578, 389, 739, 548, 13, 1071, 729, 67, 1808, 24899, 739, 548, 13, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 203, 3639, 1430, 3677, 63, 67, 739, 548, 15533, 203, 203, 3639, 3626, 2177, 7977, 12, 3767, 1769, 203, 203, 3639, 327, 261, 3767, 1769, 203, 565, 289, 203, 203, 203, 3639, 779, 15260, 30, 389, 739, 548, 30, 3124, 1368, 20092, 2874, 18, 203, 3639, 1135, 30, 1250, 16, 638, 309, 2216, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.4.21 <0.7.5; pragma experimental ABIEncoderV2; //There is only one Jokerzon cotract //contains all the purchases that has been committed contract Jokerzon { uint256 count; Product[] public products; Purchase[] public purchases; /** * Product section */ // The product seller is msg.sender // The product is not yet sold struct Product { string sellerFullName; string productName; string description; uint256 price; string city; string country; uint256 estimatedDays; address payable sellerAddress; uint256 productID; bool isSold; } constructor() public { count = 0; } function addProduct( string memory _sellerFullName, string memory _productName, string memory _description, uint256 _price, string memory _city, string memory _country, uint256 _estimatedDays ) public returns (Product memory) { // Validating that all the fields are valid require( bytes(_sellerFullName).length >= 4 && bytes(_sellerFullName).length <= 20 ); require( bytes(_productName).length >= 3 && bytes(_productName).length <= 40 ); require( bytes(_description).length >= 5 && bytes(_description).length <= 1000 ); require(bytes(_city).length > 0); require(bytes(_country).length > 0); require(_price > 0 && _price < 1000000); require(_estimatedDays >= 1 && _estimatedDays <= 60); // Creating the new product after being validated Product memory newProduct; newProduct.sellerFullName = _sellerFullName; newProduct.productName = _productName; newProduct.description = _description; newProduct.price = _price; newProduct.city = _city; newProduct.country = _country; newProduct.estimatedDays = _estimatedDays; newProduct.sellerAddress = msg.sender; newProduct.isSold = false; newProduct.productID = count++; products.push(newProduct); return newProduct; } function totalProducts() public view returns (uint32) { return (uint32)(products.length); } // Returns all the prouducts in the jokerzon contract function getAllProducts() external view returns (Product[] memory) { return products; } /** * Product section */ /** * Purchase section */ struct Purchase { string sellerFullName; string productName; string description; uint256 price; string city; string country; uint256 estimatedDays; address payable sellerAddress; uint256 productID; address payable buyerAddress; uint256 dateOfPurchase; } function addPurchase( string memory _sellerFullName, string memory _productName, string memory _description, uint256 _price, string memory _city, string memory _country, uint256 _estimatedDays, address payable _sellerAddress, uint256 _productID ) public payable { require( !checkIfSold(_productID), "The product has already been purchased" ); // Validating that all the fields are valid require( bytes(_sellerFullName).length >= 4 && bytes(_sellerFullName).length <= 20, "Seller name must be at least 4 characters and at the most 20" ); require( bytes(_productName).length >= 3 && bytes(_productName).length <= 40, "product name must be at least 3 characters and at the most 40" ); require( bytes(_description).length >= 5 && bytes(_description).length <= 1000, "description must be at least 5 characters and at the most 1000" ); require(bytes(_city).length > 0, "city must be at least 0 characters"); require( bytes(_country).length > 0, "country must be at least 0 characters" ); require( _price > 0 && _price < 1000000, "price must be at least 0 and at the most 1000000" ); require( _estimatedDays >= 1 && _estimatedDays <= 60, "Estimated daus must be at least 1 and at the most 60" ); //Checking if the buyer has enough money to commit for the TX require( msg.sender.balance >= _price, "You've not enough money bruhhh :(" ); Purchase memory newPurchase = Purchase( _sellerFullName, _productName, _description, _price, _city, _country, _estimatedDays, _sellerAddress, _productID, msg.sender, block.timestamp ); setSoldById(_productID); //The product sold for the buyer, then transfer money [Seller] -> [Buyer] purchases.push(newPurchase); } function getAllPurchases() external view returns (Purchase[] memory) { return purchases; } // Returning the product by the id in Jokerzon contract function getProductById(uint256 index) external view returns (Product memory) { require(index >= 0 && index <= products.length - 1); return products[index]; } function setSoldById(uint256 index) internal { require(index >= 0 && index <= products.length - 1); products[index].isSold = true; } function checkIfSold(uint256 index) internal view returns (bool) { require(index >= 0 && index <= products.length - 1); return products[index].isSold; } // Searching through all the products and checking if the given address is the seller address, if so, then returning // the full name, otherwise - empty string returned function getFullName(address _sellerAddress) external view returns (string memory) { for (uint256 i = 0; i < products.length; i++) { if (products[i].sellerAddress == _sellerAddress) { return products[i].sellerFullName; } } return ""; } }
There is only one Jokerzon cotractcontains all the purchases that has been committed The product seller is msg.sender The product is not yet sold
contract Jokerzon { uint256 count; Product[] public products; Purchase[] public purchases; struct Product { string sellerFullName; string productName; string description; uint256 price; string city; string country; uint256 estimatedDays; address payable sellerAddress; uint256 productID; bool isSold; } constructor() public { count = 0; } function addProduct( string memory _sellerFullName, string memory _productName, string memory _description, uint256 _price, string memory _city, string memory _country, uint256 _estimatedDays ) public returns (Product memory) { require( bytes(_sellerFullName).length >= 4 && bytes(_sellerFullName).length <= 20 ); require( bytes(_productName).length >= 3 && bytes(_productName).length <= 40 ); require( bytes(_description).length >= 5 && bytes(_description).length <= 1000 ); require(bytes(_city).length > 0); require(bytes(_country).length > 0); require(_price > 0 && _price < 1000000); require(_estimatedDays >= 1 && _estimatedDays <= 60); Product memory newProduct; newProduct.sellerFullName = _sellerFullName; newProduct.productName = _productName; newProduct.description = _description; newProduct.price = _price; newProduct.city = _city; newProduct.country = _country; newProduct.estimatedDays = _estimatedDays; newProduct.sellerAddress = msg.sender; newProduct.isSold = false; newProduct.productID = count++; products.push(newProduct); return newProduct; } function totalProducts() public view returns (uint32) { return (uint32)(products.length); } function getAllProducts() external view returns (Product[] memory) { return products; } struct Purchase { string sellerFullName; string productName; string description; uint256 price; string city; string country; uint256 estimatedDays; address payable sellerAddress; uint256 productID; address payable buyerAddress; uint256 dateOfPurchase; } function addPurchase( string memory _sellerFullName, string memory _productName, string memory _description, uint256 _price, string memory _city, string memory _country, uint256 _estimatedDays, address payable _sellerAddress, uint256 _productID ) public payable { require( !checkIfSold(_productID), "The product has already been purchased" ); require( bytes(_sellerFullName).length >= 4 && bytes(_sellerFullName).length <= 20, "Seller name must be at least 4 characters and at the most 20" ); require( bytes(_productName).length >= 3 && bytes(_productName).length <= 40, "product name must be at least 3 characters and at the most 40" ); require( bytes(_description).length >= 5 && bytes(_description).length <= 1000, "description must be at least 5 characters and at the most 1000" ); require(bytes(_city).length > 0, "city must be at least 0 characters"); require( bytes(_country).length > 0, "country must be at least 0 characters" ); require( _price > 0 && _price < 1000000, "price must be at least 0 and at the most 1000000" ); require( _estimatedDays >= 1 && _estimatedDays <= 60, "Estimated daus must be at least 1 and at the most 60" ); require( msg.sender.balance >= _price, "You've not enough money bruhhh :(" ); Purchase memory newPurchase = Purchase( _sellerFullName, _productName, _description, _price, _city, _country, _estimatedDays, _sellerAddress, _productID, msg.sender, block.timestamp ); setSoldById(_productID); purchases.push(newPurchase); } function getAllPurchases() external view returns (Purchase[] memory) { return purchases; } function getProductById(uint256 index) external view returns (Product memory) { require(index >= 0 && index <= products.length - 1); return products[index]; } function setSoldById(uint256 index) internal { require(index >= 0 && index <= products.length - 1); products[index].isSold = true; } function checkIfSold(uint256 index) internal view returns (bool) { require(index >= 0 && index <= products.length - 1); return products[index].isSold; } function getFullName(address _sellerAddress) external view returns (string memory) { for (uint256 i = 0; i < products.length; i++) { if (products[i].sellerAddress == _sellerAddress) { return products[i].sellerFullName; } } return ""; } function getFullName(address _sellerAddress) external view returns (string memory) { for (uint256 i = 0; i < products.length; i++) { if (products[i].sellerAddress == _sellerAddress) { return products[i].sellerFullName; } } return ""; } function getFullName(address _sellerAddress) external view returns (string memory) { for (uint256 i = 0; i < products.length; i++) { if (products[i].sellerAddress == _sellerAddress) { return products[i].sellerFullName; } } return ""; } }
14,111,293
[ 1, 9828, 353, 1338, 1245, 804, 601, 264, 94, 265, 1825, 1575, 12298, 777, 326, 5405, 343, 3304, 716, 711, 2118, 16015, 1021, 3017, 29804, 353, 1234, 18, 15330, 1021, 3017, 353, 486, 4671, 272, 1673, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 804, 601, 264, 94, 265, 288, 203, 565, 2254, 5034, 1056, 31, 203, 565, 8094, 8526, 1071, 10406, 31, 203, 565, 26552, 8526, 1071, 5405, 343, 3304, 31, 203, 565, 1958, 8094, 288, 203, 3639, 533, 29804, 19223, 31, 203, 3639, 533, 3017, 461, 31, 203, 3639, 533, 2477, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 533, 12797, 31, 203, 3639, 533, 5251, 31, 203, 3639, 2254, 5034, 13137, 9384, 31, 203, 3639, 1758, 8843, 429, 29804, 1887, 31, 203, 3639, 2254, 5034, 3017, 734, 31, 203, 3639, 1426, 11604, 1673, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 1056, 273, 374, 31, 203, 565, 289, 203, 203, 565, 445, 527, 4133, 12, 203, 3639, 533, 3778, 389, 1786, 749, 19223, 16, 203, 3639, 533, 3778, 389, 5896, 461, 16, 203, 3639, 533, 3778, 389, 3384, 16, 203, 3639, 2254, 5034, 389, 8694, 16, 203, 3639, 533, 3778, 389, 14240, 16, 203, 3639, 533, 3778, 389, 9082, 16, 203, 3639, 2254, 5034, 389, 395, 17275, 9384, 203, 565, 262, 1071, 1135, 261, 4133, 3778, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1731, 24899, 1786, 749, 19223, 2934, 2469, 1545, 1059, 597, 203, 7734, 1731, 24899, 1786, 749, 19223, 2934, 2469, 1648, 4200, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1731, 24899, 5896, 461, 2934, 2469, 1545, 890, 597, 1731, 24899, 5896, 461, 2934, 2469, 1648, 8063, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1731, 24899, 3384, 2934, 2469, 1545, 1381, 597, 2 ]
./full_match/4/0x6d60fBb5739752e6FD821b772D04a4a1401188aC/sources/mega/v2/ERC1155CrowdsalesV2SingleFile.sol
* @dev See {IERC1155MetadataURI-uri}. This implementation returns the same URI for all token types. It relies on the token type ID substitution mechanism Clients calling this function must replace the `\{id\}` substring with the actual token type ID./
function uri(uint256 id) external view virtual override returns (string memory) { return _uri; }
740,903
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 2277, 3098, 17, 1650, 5496, 1220, 4471, 1135, 326, 1967, 3699, 364, 777, 1147, 1953, 18, 2597, 14719, 281, 603, 326, 1147, 618, 1599, 12785, 12860, 30655, 4440, 333, 445, 1297, 1453, 326, 1375, 64, 95, 350, 64, 11760, 3019, 598, 326, 3214, 1147, 618, 1599, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2003, 12, 11890, 5034, 612, 13, 3903, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 1650, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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; } }
* @title ReserveConfiguration library @author Aave @notice Implements the bitmap logic to handle the reserve configuration/
library ReserveConfiguration { 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; pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; import {DataTypes} from '../types/DataTypes.sol'; 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; } function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return self.data & ~LTV_MASK; } 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); } function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION; } 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); } function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION; } 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); } function getDecimals(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION; } 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); } function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~ACTIVE_MASK) != 0; } 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); } function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~FROZEN_MASK) != 0; } 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); } function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~BORROWING_MASK) != 0; } 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); } function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) { return (self.data & ~STABLE_BORROWING_MASK) != 0; } 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); } function getReserveFactor(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) { return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION; } 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 ); } 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 ); } 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 ); } 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 ); } }
68,383
[ 1, 607, 6527, 1750, 5313, 225, 432, 836, 225, 29704, 326, 9389, 4058, 358, 1640, 326, 20501, 1664, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 1124, 6527, 1750, 288, 203, 203, 225, 2254, 5034, 5381, 8961, 53, 3060, 2689, 67, 23840, 67, 7570, 67, 15650, 67, 15258, 273, 2872, 31, 203, 225, 2254, 5034, 5381, 8961, 53, 3060, 2689, 67, 38, 673, 3378, 67, 7570, 67, 15650, 67, 15258, 273, 3847, 31, 203, 225, 2254, 5034, 5381, 2438, 2123, 3412, 67, 23816, 55, 67, 7570, 67, 15650, 67, 15258, 273, 9934, 31, 203, 225, 2254, 5034, 5381, 4437, 67, 13301, 67, 7570, 67, 15650, 67, 15258, 273, 13850, 31, 203, 225, 2254, 5034, 5381, 4437, 67, 42, 1457, 62, 1157, 67, 7570, 67, 15650, 67, 15258, 273, 15981, 31, 203, 225, 2254, 5034, 5381, 605, 916, 11226, 1360, 67, 13560, 67, 7570, 67, 15650, 67, 15258, 273, 17066, 31, 203, 225, 2254, 5034, 5381, 2347, 2782, 67, 38, 916, 11226, 1360, 67, 13560, 67, 7570, 67, 15650, 67, 15258, 273, 14995, 31, 203, 225, 2254, 5034, 5381, 2438, 2123, 3412, 67, 26835, 67, 7570, 67, 15650, 67, 15258, 273, 5178, 31, 203, 203, 225, 2254, 5034, 5381, 4552, 67, 5063, 67, 12050, 58, 273, 10147, 31, 203, 225, 2254, 5034, 5381, 4552, 67, 5063, 67, 2053, 53, 3060, 2689, 67, 23840, 273, 10147, 31, 203, 225, 2254, 5034, 5381, 4552, 67, 5063, 67, 2053, 53, 3060, 2689, 67, 38, 673, 3378, 273, 10147, 31, 203, 225, 2254, 5034, 5381, 4552, 67, 5063, 67, 23816, 55, 273, 4561, 31, 203, 225, 2254, 5034, 5381, 4552, 67, 5063, 67, 862, 2123, 3412, 67, 26835, 273, 10147, 31, 203, 203, 683, 2 ]
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // 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.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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. 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"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. 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"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: 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, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: 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, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // 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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
@dev Helper to force the payout of shares outstanding across all fees. For the current release, all shares in the VaultProxy are assumed to be shares outstanding from fees. If not, then they were sent there by mistake and are otherwise unrecoverable. We can therefore take the VaultProxy's shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); }
1,697,237
[ 1, 2276, 358, 2944, 326, 293, 2012, 434, 24123, 20974, 10279, 777, 1656, 281, 18, 2457, 326, 783, 3992, 16, 777, 24123, 316, 326, 17329, 3886, 854, 12034, 358, 506, 24123, 20974, 628, 1656, 281, 18, 971, 486, 16, 1508, 2898, 4591, 3271, 1915, 635, 27228, 911, 471, 854, 3541, 640, 25864, 18, 1660, 848, 13526, 4862, 326, 17329, 3886, 1807, 24123, 11013, 487, 326, 2078, 24051, 1182, 15167, 358, 293, 2012, 358, 326, 284, 1074, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 5734, 52, 2012, 1595, 24051, 1182, 15167, 12, 2867, 389, 832, 337, 1539, 3886, 13, 3238, 288, 203, 3639, 1758, 9229, 3886, 273, 11031, 3714, 3886, 1290, 42, 1074, 24899, 832, 337, 1539, 3886, 1769, 203, 203, 3639, 2254, 5034, 2078, 24051, 1182, 15167, 273, 4232, 39, 3462, 12, 26983, 3886, 2934, 12296, 951, 12, 26983, 3886, 1769, 203, 3639, 309, 261, 4963, 24051, 1182, 15167, 422, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 1656, 281, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1430, 532, 337, 1539, 3886, 774, 14667, 774, 24051, 1182, 15167, 63, 67, 832, 337, 1539, 3886, 6362, 3030, 281, 63, 77, 13563, 31, 203, 3639, 289, 203, 203, 3639, 1001, 13866, 24051, 24899, 832, 337, 1539, 3886, 16, 9229, 3886, 16, 8843, 1340, 16, 2078, 24051, 1182, 15167, 1769, 203, 203, 3639, 3626, 4826, 24051, 1182, 15167, 10997, 16507, 350, 1290, 42, 1074, 12, 203, 5411, 389, 832, 337, 1539, 3886, 16, 203, 5411, 8843, 1340, 16, 203, 5411, 2078, 24051, 1182, 15167, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x7A685C80A4414bF7260F10A4bB67F889C01435F6/sources/contracts/Contract.sol
Refers to the tool
bool isData;
849,305
[ 1, 1957, 414, 358, 326, 5226, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1426, 353, 751, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Wallets.sol
@title Wallet library @notice Library responsible for handling integration between Bridge contract and ECDSA wallets.
library Wallets { using BTCUtils for bytes; import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {EcdsaDkg} from "@keep-network/ecdsa/contracts/libraries/EcdsaDkg.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; enum WalletState { Unknown, Live, MovingFunds, Closing, Closed, Terminated } struct Wallet { bytes32 ecdsaWalletID; bytes32 mainUtxoHash; uint64 pendingRedemptionsValue; uint32 createdAt; uint32 movingFundsRequestedAt; uint32 closingStartedAt; uint32 pendingMovedFundsSweepRequestsCount; WalletState state; bytes32 movingFundsTargetWalletsCommitmentHash; } event NewWalletRequested(); event NewWalletRegistered( bytes32 indexed ecdsaWalletID, bytes20 indexed walletPubKeyHash ); event WalletMovingFunds( bytes32 indexed ecdsaWalletID, bytes20 indexed walletPubKeyHash ); event WalletClosing( bytes32 indexed ecdsaWalletID, bytes20 indexed walletPubKeyHash ); event WalletClosed( bytes32 indexed ecdsaWalletID, bytes20 indexed walletPubKeyHash ); event WalletTerminated( bytes32 indexed ecdsaWalletID, bytes20 indexed walletPubKeyHash ); function requestNewWallet( BridgeState.Storage storage self, BitcoinTx.UTXO calldata activeWalletMainUtxo ) external { require( self.ecdsaWalletRegistry.getWalletCreationState() == EcdsaDkg.State.IDLE, "Wallet creation already in progress" ); bytes20 activeWalletPubKeyHash = self.activeWalletPubKeyHash; if (activeWalletPubKeyHash != bytes20(0)) { uint64 activeWalletBtcBalance = getWalletBtcBalance( self, activeWalletPubKeyHash, activeWalletMainUtxo ); uint32 activeWalletCreatedAt = self .registeredWallets[activeWalletPubKeyHash] .createdAt; bool activeWalletOldEnough = block.timestamp >= activeWalletCreatedAt + self.walletCreationPeriod; require( (activeWalletOldEnough && activeWalletBtcBalance >= self.walletCreationMinBtcBalance) || activeWalletBtcBalance >= self.walletCreationMaxBtcBalance, "Wallet creation conditions are not met" ); emit NewWalletRequested(); self.ecdsaWalletRegistry.requestNewWallet(); } function requestNewWallet( BridgeState.Storage storage self, BitcoinTx.UTXO calldata activeWalletMainUtxo ) external { require( self.ecdsaWalletRegistry.getWalletCreationState() == EcdsaDkg.State.IDLE, "Wallet creation already in progress" ); bytes20 activeWalletPubKeyHash = self.activeWalletPubKeyHash; if (activeWalletPubKeyHash != bytes20(0)) { uint64 activeWalletBtcBalance = getWalletBtcBalance( self, activeWalletPubKeyHash, activeWalletMainUtxo ); uint32 activeWalletCreatedAt = self .registeredWallets[activeWalletPubKeyHash] .createdAt; bool activeWalletOldEnough = block.timestamp >= activeWalletCreatedAt + self.walletCreationPeriod; require( (activeWalletOldEnough && activeWalletBtcBalance >= self.walletCreationMinBtcBalance) || activeWalletBtcBalance >= self.walletCreationMaxBtcBalance, "Wallet creation conditions are not met" ); emit NewWalletRequested(); self.ecdsaWalletRegistry.requestNewWallet(); } } function registerNewWallet( BridgeState.Storage storage self, bytes32 ecdsaWalletID, bytes32 publicKeyX, bytes32 publicKeyY ) external { require( msg.sender == address(self.ecdsaWalletRegistry), "Caller is not the ECDSA Wallet Registry" ); bytes20 walletPubKeyHash = bytes20( EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View() ); Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; require( wallet.state == WalletState.Unknown, "ECDSA wallet has been already registered" ); wallet.ecdsaWalletID = ecdsaWalletID; wallet.state = WalletState.Live; wallet.createdAt = uint32(block.timestamp); self.activeWalletPubKeyHash = walletPubKeyHash; self.liveWalletsCount++; emit NewWalletRegistered(ecdsaWalletID, walletPubKeyHash); } function notifyWalletRedemptionTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; require( walletState == WalletState.Live || walletState == WalletState.MovingFunds || walletState == WalletState.Terminated, "Wallet must be in Live or MovingFunds or Terminated state" ); if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds ) { self.ecdsaWalletRegistry.seize( self.redemptionTimeoutSlashingAmount, self.redemptionTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); } if (walletState == WalletState.Live) { moveFunds(self, walletPubKeyHash); } } function notifyWalletRedemptionTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; require( walletState == WalletState.Live || walletState == WalletState.MovingFunds || walletState == WalletState.Terminated, "Wallet must be in Live or MovingFunds or Terminated state" ); if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds ) { self.ecdsaWalletRegistry.seize( self.redemptionTimeoutSlashingAmount, self.redemptionTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); } if (walletState == WalletState.Live) { moveFunds(self, walletPubKeyHash); } } function notifyWalletRedemptionTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; require( walletState == WalletState.Live || walletState == WalletState.MovingFunds || walletState == WalletState.Terminated, "Wallet must be in Live or MovingFunds or Terminated state" ); if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds ) { self.ecdsaWalletRegistry.seize( self.redemptionTimeoutSlashingAmount, self.redemptionTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); } if (walletState == WalletState.Live) { moveFunds(self, walletPubKeyHash); } } function notifyWalletHeartbeatFailed( BridgeState.Storage storage self, bytes32 publicKeyX, bytes32 publicKeyY ) external { require( msg.sender == address(self.ecdsaWalletRegistry), "Caller is not the ECDSA Wallet Registry" ); bytes20 walletPubKeyHash = bytes20( EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View() ); require( self.registeredWallets[walletPubKeyHash].state == WalletState.Live, "Wallet must be in Live state" ); moveFunds(self, walletPubKeyHash); } function notifyWalletCloseable( BridgeState.Storage storage self, bytes20 walletPubKeyHash, BitcoinTx.UTXO calldata walletMainUtxo ) external { require( self.activeWalletPubKeyHash != walletPubKeyHash, "Active wallet cannot be considered closeable" ); Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; require( wallet.state == WalletState.Live, "Wallet must be in Live state" ); bool walletOldEnough = block.timestamp >= wallet.createdAt + self.walletMaxAge; require( walletOldEnough || getWalletBtcBalance(self, walletPubKeyHash, walletMainUtxo) < self.walletClosureMinBtcBalance, "Wallet needs to be old enough or have too few satoshis" ); moveFunds(self, walletPubKeyHash); } function notifyWalletClosingPeriodElapsed( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; require( wallet.state == WalletState.Closing, "Wallet must be in Closing state" ); require( block.timestamp > wallet.closingStartedAt + self.walletClosingPeriod, "Closing period has not elapsed yet" ); finalizeWalletClosing(self, walletPubKeyHash); } function notifyWalletFundsMoved( BridgeState.Storage storage self, bytes20 walletPubKeyHash, bytes32 targetWalletsHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; require( wallet.state == WalletState.MovingFunds, "Wallet must be in MovingFunds state" ); bytes32 targetWalletsCommitmentHash = wallet .movingFundsTargetWalletsCommitmentHash; require( targetWalletsCommitmentHash != bytes32(0), "Target wallets commitment not submitted yet" ); require( targetWalletsCommitmentHash == targetWalletsHash, "Target wallets don't correspond to the commitment" ); delete wallet.mainUtxoHash; beginWalletClosing(self, walletPubKeyHash); } function notifyWalletMovingFundsBelowDust( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { WalletState walletState = self .registeredWallets[walletPubKeyHash] .state; require( walletState == Wallets.WalletState.MovingFunds, "Wallet must be in MovingFunds state" ); beginWalletClosing(self, walletPubKeyHash); } function notifyWalletMovingFundsTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallets.Wallet storage wallet = self.registeredWallets[ walletPubKeyHash ]; require( wallet.state == Wallets.WalletState.MovingFunds, "Wallet must be in MovingFunds state" ); self.ecdsaWalletRegistry.seize( self.movingFundsTimeoutSlashingAmount, self.movingFundsTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); terminateWallet(self, walletPubKeyHash); } function notifyWalletMovedFundsSweepTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; require( walletState == WalletState.Live || walletState == WalletState.MovingFunds || walletState == WalletState.Terminated, "Wallet must be in Live or MovingFunds or Terminated state" ); if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds ) { self.ecdsaWalletRegistry.seize( self.movedFundsSweepTimeoutSlashingAmount, self.movedFundsSweepTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); terminateWallet(self, walletPubKeyHash); } } function notifyWalletMovedFundsSweepTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; require( walletState == WalletState.Live || walletState == WalletState.MovingFunds || walletState == WalletState.Terminated, "Wallet must be in Live or MovingFunds or Terminated state" ); if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds ) { self.ecdsaWalletRegistry.seize( self.movedFundsSweepTimeoutSlashingAmount, self.movedFundsSweepTimeoutNotifierRewardMultiplier, msg.sender, wallet.ecdsaWalletID, walletMembersIDs ); terminateWallet(self, walletPubKeyHash); } } function notifyWalletFraudChallengeDefeatTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs, address challenger ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds || walletState == Wallets.WalletState.Closing ) { self.ecdsaWalletRegistry.seize( self.fraudSlashingAmount, self.fraudNotifierRewardMultiplier, challenger, wallet.ecdsaWalletID, walletMembersIDs ); terminateWallet(self, walletPubKeyHash); revert( "Wallet must be in Live or MovingFunds or Closing or Terminated state" ); } } function notifyWalletFraudChallengeDefeatTimeout( BridgeState.Storage storage self, bytes20 walletPubKeyHash, uint32[] calldata walletMembersIDs, address challenger ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; WalletState walletState = wallet.state; if ( walletState == Wallets.WalletState.Live || walletState == Wallets.WalletState.MovingFunds || walletState == Wallets.WalletState.Closing ) { self.ecdsaWalletRegistry.seize( self.fraudSlashingAmount, self.fraudNotifierRewardMultiplier, challenger, wallet.ecdsaWalletID, walletMembersIDs ); terminateWallet(self, walletPubKeyHash); revert( "Wallet must be in Live or MovingFunds or Closing or Terminated state" ); } } } else if (walletState == Wallets.WalletState.Terminated) { } else { function moveFunds( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.mainUtxoHash == bytes32(0)) { beginWalletClosing(self, walletPubKeyHash); wallet.state = WalletState.MovingFunds; wallet.movingFundsRequestedAt = uint32(block.timestamp); emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash); } if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.liveWalletsCount--; } function moveFunds( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.mainUtxoHash == bytes32(0)) { beginWalletClosing(self, walletPubKeyHash); wallet.state = WalletState.MovingFunds; wallet.movingFundsRequestedAt = uint32(block.timestamp); emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash); } if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.liveWalletsCount--; } } else { function moveFunds( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.mainUtxoHash == bytes32(0)) { beginWalletClosing(self, walletPubKeyHash); wallet.state = WalletState.MovingFunds; wallet.movingFundsRequestedAt = uint32(block.timestamp); emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash); } if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.liveWalletsCount--; } function beginWalletClosing( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; wallet.state = WalletState.Closing; wallet.closingStartedAt = uint32(block.timestamp); emit WalletClosing(wallet.ecdsaWalletID, walletPubKeyHash); } function finalizeWalletClosing( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; wallet.state = WalletState.Closed; emit WalletClosed(wallet.ecdsaWalletID, walletPubKeyHash); self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID); } function terminateWallet( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.state == WalletState.Live) { self.liveWalletsCount--; } wallet.state = WalletState.Terminated; if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID); } function terminateWallet( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.state == WalletState.Live) { self.liveWalletsCount--; } wallet.state = WalletState.Terminated; if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID); } emit WalletTerminated(wallet.ecdsaWalletID, walletPubKeyHash); function terminateWallet( BridgeState.Storage storage self, bytes20 walletPubKeyHash ) internal { Wallet storage wallet = self.registeredWallets[walletPubKeyHash]; if (wallet.state == WalletState.Live) { self.liveWalletsCount--; } wallet.state = WalletState.Terminated; if (self.activeWalletPubKeyHash == walletPubKeyHash) { delete self.activeWalletPubKeyHash; } self.ecdsaWalletRegistry.closeWallet(wallet.ecdsaWalletID); } function getWalletBtcBalance( BridgeState.Storage storage self, bytes20 walletPubKeyHash, BitcoinTx.UTXO calldata walletMainUtxo ) internal view returns (uint64 walletBtcBalance) { bytes32 walletMainUtxoHash = self .registeredWallets[walletPubKeyHash] .mainUtxoHash; if (walletMainUtxoHash != bytes32(0)) { require( keccak256( abi.encodePacked( walletMainUtxo.txHash, walletMainUtxo.txOutputIndex, walletMainUtxo.txOutputValue ) ) == walletMainUtxoHash, "Invalid wallet main UTXO data" ); walletBtcBalance = walletMainUtxo.txOutputValue; } return walletBtcBalance; } function getWalletBtcBalance( BridgeState.Storage storage self, bytes20 walletPubKeyHash, BitcoinTx.UTXO calldata walletMainUtxo ) internal view returns (uint64 walletBtcBalance) { bytes32 walletMainUtxoHash = self .registeredWallets[walletPubKeyHash] .mainUtxoHash; if (walletMainUtxoHash != bytes32(0)) { require( keccak256( abi.encodePacked( walletMainUtxo.txHash, walletMainUtxo.txOutputIndex, walletMainUtxo.txOutputValue ) ) == walletMainUtxoHash, "Invalid wallet main UTXO data" ); walletBtcBalance = walletMainUtxo.txOutputValue; } return walletBtcBalance; } }
4,856,593
[ 1, 16936, 5313, 225, 18694, 14549, 364, 5057, 12040, 3086, 24219, 540, 6835, 471, 7773, 19748, 17662, 2413, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 678, 454, 2413, 288, 203, 565, 1450, 605, 15988, 1989, 364, 1731, 31, 203, 203, 203, 203, 5666, 288, 38, 15988, 1989, 97, 628, 8787, 10102, 17, 5185, 19, 3682, 12645, 17, 1752, 90, 17, 18281, 19, 16351, 87, 19, 38, 15988, 1989, 18, 18281, 14432, 203, 5666, 288, 23057, 19603, 40, 14931, 97, 628, 8787, 10102, 17, 5185, 19, 557, 19603, 19, 16351, 87, 19, 31417, 19, 23057, 19603, 40, 14931, 18, 18281, 14432, 203, 5666, 288, 10477, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 5471, 19, 15949, 19, 10477, 18, 18281, 14432, 203, 565, 2792, 20126, 1119, 288, 203, 3639, 9077, 16, 203, 3639, 21559, 16, 203, 3639, 490, 13767, 42, 19156, 16, 203, 3639, 385, 10910, 16, 203, 3639, 25582, 16, 203, 3639, 6820, 7458, 203, 203, 565, 289, 203, 565, 1958, 20126, 288, 203, 3639, 1731, 1578, 23593, 16936, 734, 31, 203, 3639, 1731, 1578, 2774, 57, 978, 83, 2310, 31, 203, 3639, 2254, 1105, 4634, 426, 19117, 573, 620, 31, 203, 3639, 2254, 1578, 26083, 31, 203, 3639, 2254, 1578, 12499, 42, 1074, 8943, 329, 861, 31, 203, 3639, 2254, 1578, 7647, 9217, 861, 31, 203, 3639, 2254, 1578, 4634, 25317, 42, 19156, 55, 25236, 6421, 1380, 31, 203, 3639, 20126, 1119, 919, 31, 203, 3639, 1731, 1578, 12499, 42, 19156, 2326, 26558, 2413, 5580, 475, 2310, 31, 203, 565, 289, 203, 203, 565, 871, 1166, 16936, 11244, 5621, 203, 203, 565, 871, 1166, 16936, 10868, 12, 203, 3639, 1731, 1578, 8808, 2 ]
pragma solidity ^0.4.19; contract KeyManager { event LogKeyAdded( address peer, bytes32 key ); event LogKeyUpdated( address peer, bytes32 formerKey, bytes32 newKey ); event LogKeyDeleted( address peer, bytes32 key ); struct KeyEntry { bytes32 publicKey; bool isValue; } mapping(address => KeyEntry) internal keyRegister; bytes32 internal constant NULL_KEY = "0x0"; function KeyManager() public { // Nothing } function () public { revert(); } function AddKey(bytes32 pubKey) public { // We make sure that no key has been registered for this address before // If a key has already been declared for this address then // we fail, because this would be an UPDATE and NOT an ADD operation. require(!keyRegister[msg.sender].isValue); keyRegister[msg.sender] = KeyEntry({publicKey: pubKey, isValue: true}); LogKeyAdded(msg.sender, pubKey); } function UpdateKey(bytes32 pubKey) public { // We make sure that no key has been added for this address before // in order to make sure that this is an UPDATE and NOT an ADD operation. require(keyRegister[msg.sender].isValue); // Get the former public key of the msg.sender in order to use it in the LogKeyUpdated event bytes32 formerPubKey = keyRegister[msg.sender].publicKey; keyRegister[msg.sender] = KeyEntry({publicKey: pubKey, isValue: true}); LogKeyUpdated(msg.sender, formerPubKey, pubKey); } function DeleteKey(bytes32 pubKey) public { // We make sure that a key has been added for this address before // in order to make sure that this is NOT an UPDATE and NOT a ADD operation. require(keyRegister[msg.sender].isValue); // Set the publicKey to this address to the NULL_KEY value, and set the // isValue to false in order to satisfy the require of the AddVirtualAddress function // next time this peer we'll call the contract to add his public key to the register keyRegister[msg.sender] = KeyEntry({publicKey: pubKey, isValue: false}); LogKeyDeleted(msg.sender, pubKey); } // Returns the public key (for encryption of private Tx) of the corresponding address // Note that using this function right before doing a payment would leak a lot of information // and almost reveal the recipient of the payment. // AddKey, UpdateKey, DeleteKey trigger events in order to inform all the listeners that the // registry has been updated. By listening to these events a peer of the network SHOULD never call // the GetKey function... function GetKey(address peer) public constant returns (bytes32) { if (!keyRegister[peer].isValue) { // If the virtualAddress doesn't exist (ie: No pubKey declared for this address) // Then we return the null address return NULL_KEY; } return keyRegister[peer].publicKey; } }
Returns the public key (for encryption of private Tx) of the corresponding address Note that using this function right before doing a payment would leak a lot of information and almost reveal the recipient of the payment. AddKey, UpdateKey, DeleteKey trigger events in order to inform all the listeners that the registry has been updated. By listening to these events a peer of the network SHOULD never call the GetKey function... If the virtualAddress doesn't exist (ie: No pubKey declared for this address) Then we return the null address
function GetKey(address peer) public constant returns (bytes32) { if (!keyRegister[peer].isValue) { return NULL_KEY; } return keyRegister[peer].publicKey; }
14,125,067
[ 1, 1356, 326, 1071, 498, 261, 1884, 8731, 434, 3238, 6424, 13, 434, 326, 4656, 1758, 3609, 716, 1450, 333, 445, 2145, 1865, 9957, 279, 5184, 4102, 20891, 279, 17417, 434, 1779, 471, 23889, 283, 24293, 326, 8027, 434, 326, 5184, 18, 1436, 653, 16, 2315, 653, 16, 2504, 653, 3080, 2641, 316, 1353, 358, 13235, 777, 326, 4679, 716, 326, 4023, 711, 2118, 3526, 18, 2525, 13895, 358, 4259, 2641, 279, 4261, 434, 326, 2483, 6122, 31090, 5903, 745, 326, 29648, 445, 2777, 971, 326, 5024, 1887, 3302, 1404, 1005, 261, 1385, 30, 2631, 18659, 7886, 364, 333, 1758, 13, 9697, 732, 327, 326, 446, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 29648, 12, 2867, 4261, 13, 1071, 5381, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 309, 16051, 856, 3996, 63, 12210, 8009, 291, 620, 13, 288, 203, 5411, 327, 3206, 67, 3297, 31, 203, 3639, 289, 203, 3639, 327, 498, 3996, 63, 12210, 8009, 482, 653, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x37cd9141AFd52d7B71aCa09FB245C786F2777286/sources/RDOGE.sol
swap token -> eth team eth marketing eth
function swapAndLiquify(uint256 tAmount) private lockTheSwap { swapTokensForEth(tAmount); uint256 amountReceived = address(this).balance; uint256 amountUSDTTeam = amountReceived.mul(50).div(100); uint256 amountUSDTMarketing = amountReceived.sub(amountUSDTTeam); if(amountUSDTMarketing > 0) transferToAddressETH(marketingWalletAddress, amountUSDTMarketing); if(amountUSDTTeam > 0) transferToAddressETH(teamWalletAddress, amountUSDTTeam); }
2,587,227
[ 1, 22270, 1147, 317, 13750, 5927, 13750, 13667, 310, 13750, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7720, 1876, 48, 18988, 1164, 12, 11890, 5034, 268, 6275, 13, 3238, 2176, 1986, 12521, 288, 203, 203, 3639, 7720, 5157, 1290, 41, 451, 12, 88, 6275, 1769, 203, 3639, 2254, 5034, 3844, 8872, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 1850, 203, 3639, 2254, 5034, 3844, 3378, 40, 1470, 3820, 273, 3844, 8872, 18, 16411, 12, 3361, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 3844, 3378, 9081, 3882, 21747, 273, 3844, 8872, 18, 1717, 12, 8949, 3378, 40, 1470, 3820, 1769, 203, 203, 3639, 309, 12, 8949, 3378, 9081, 3882, 21747, 405, 374, 13, 203, 5411, 7412, 774, 1887, 1584, 44, 12, 3355, 21747, 16936, 1887, 16, 3844, 3378, 9081, 3882, 21747, 1769, 203, 203, 3639, 309, 12, 8949, 3378, 40, 1470, 3820, 405, 374, 13, 203, 5411, 7412, 774, 1887, 1584, 44, 12, 10035, 16936, 1887, 16, 3844, 3378, 40, 1470, 3820, 1769, 203, 203, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * 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 { /** * 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; } /** * 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"); } /** * 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; } /** * 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; } /** * 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"); } /** * 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; } /** * 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"); } /** * Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * Collection of functions related to the address type */ library Address { /** * 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); } /** * 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"); } /** * 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"); } /** * 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); } /** * 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"); } /** * Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * 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; /** * 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; } /** * Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * 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; } /** * See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * 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; } /** * See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * 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; } /** * 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; } /** * 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; } /** * 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; } /** * 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"); amount = _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); } /** 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"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * 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"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * 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); } /** * 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_; } /** * Hook that is called before any transfer of tokens. * * 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 returns (uint256) { } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * 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); /** * Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * 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); } /** * 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/StabilizeToken.sol pragma solidity ^0.6.0; // Stabilize Token with Governance. contract StabilizeToken is ERC20("Stabilize Token", "STBZ"), Ownable { //using SafeMath for uint256; // Variables bool private burnStarted = false; // Starts during week 53 uint256 public burnRate = 0; // Can be between 0 - 100000 (0% - 100%) uint256 constant divisionFactor = 100000; // Events event BurnStarted(); /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Operator). function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { _mint(_to, _amount); return true; } // This function will burn a percentage of tokens not sent from the owner after 52 weeks are over function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override returns (uint256) { super._beforeTokenTransfer(from, to, amount); // Call parent hook if(burnStarted == true && burnRate > 0){ if(from != owner()){ // When the Operator is not transferring tokens, it is burned after 52 week uint256 burnAmount = amount.mul(burnRate).div(divisionFactor); if(burnAmount.add(amount) > balanceOf(from)){ uint256 overage = burnAmount.add(amount).sub(balanceOf(from)); amount = amount.sub(overage); // Only subtract from the overage amount sent if user balance is not enough } _burn(from,burnAmount); } } return amount; } // Operator has initiated the per transaction burning function initiateBurn(uint256 rate) public onlyOwner returns (bool) { if(burnStarted == false){ burnStarted = true; } burnRate = rate; emit BurnStarted(); return true; } }
Starts during week 53
bool private burnStarted = false;
618,361
[ 1, 11203, 4982, 4860, 15935, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 3238, 18305, 9217, 273, 629, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // @title TechPay deployed smart contract validation service. contract ContractValidation { // ValidatedContract structure represents an information about deployed // smart contract, validated through one of our API nodes. struct ValidatedContract { string name; // name of the contract bytes32 version; // version information of the contract bytes32 license; // license of the contract string contact; // support contact of the contract bytes32 compiler; // compiler used to compile/validate the contract bytes32 clVersion; // version of the compiler used to compile the contract bool isOptimized; // was the compiler run with "optimized" option int32 optRounds; // optimization rounds used by the compiler to build the contract bytes32 srcHash; // compressed source code hash uint validated; // Unix timestamp of the contract validation } // admin is the address managing the contract validation container. address public admin; // validators are the addresses of the nodes allowed to submit contract validations. mapping(address => bool) public validators; // contracts maps contract address to the validation record. mapping(address => ValidatedContract) public contracts; // ContractValidated signals contract validation for the given contract address. event ContractValidated(address indexed addr, bytes32 srcHash); // ContractValidationDropped signals contract validation has been canceled. event ContractValidationDropped(address indexed addr); // constructor create new instance of the validation contract. constructor() public { // keep the contract creator as the admin admin = msg.sender; // add the admin as the first validator validators[msg.sender] = true; } // addValidator adds new validator address to the contract. function addValidator(address val) public { // only administrator can do this require(msg.sender == admin, "only admin can add validators"); // add the new validator to the list validators[val] = true; } // dropValidator disables specified validator from being able to send new validations. function dropValidator(address val) public { // only administrator can do this require(msg.sender == admin, "only admin can drop validators"); // delete the validator off the list delete (validators[val]); } // validate registers new validated deployed contract and stores the validation // information in so it can be used later. function validated( address addr, string memory name, bytes32 version, bytes32 license, string memory contact, bytes32 compiler, bytes32 clVersion, bool isOptimized, int32 optRounds, bytes memory source) public { // only validators ca do this require(validators[msg.sender], "only validators can validate"); // get the storage for the contract ValidatedContract storage inContract = contracts[addr]; // update the contract details from incoming data inContract.name = name; inContract.version = version; inContract.license = license; inContract.contact = contact; inContract.compiler = compiler; inContract.clVersion = clVersion; inContract.isOptimized = isOptimized; inContract.optRounds = optRounds; inContract.validated = now; // calculate the hash inContract.srcHash = keccak256(source); // emit the event for new validated contract emit ContractValidated(addr, inContract.srcHash); } // dropValidation removes validation information from the contract. function dropValidation(address addr) public { // only administrator can drop validation require(msg.sender == admin, "only admin can drop validation"); // drop the validation as requested delete (contracts[addr]); // emit an event about it emit ContractValidationDropped(addr); } }
ContractValidated signals contract validation for the given contract address.
event ContractValidated(address indexed addr, bytes32 srcHash);
5,537,696
[ 1, 8924, 24258, 11505, 6835, 3379, 364, 326, 864, 6835, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 13456, 24258, 12, 2867, 8808, 3091, 16, 1731, 1578, 1705, 2310, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xfE21B0A8dF3308c61CB13DF57ae5962c567A668A/sources/EphimeraToken.sol
* @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). Requirements: - the caller must be `account`./
function renounceRole(bytes32 role, address account) external virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); }
2,851,933
[ 1, 10070, 601, 281, 1375, 4615, 68, 628, 326, 4440, 2236, 18, 19576, 854, 16337, 7016, 3970, 288, 16243, 2996, 97, 471, 288, 9083, 3056, 2996, 6713, 333, 445, 1807, 13115, 353, 358, 5615, 279, 12860, 364, 9484, 358, 29612, 3675, 19583, 309, 2898, 854, 1161, 520, 5918, 261, 87, 2648, 487, 1347, 279, 13179, 2346, 353, 7524, 28238, 2934, 29076, 30, 300, 326, 4894, 1297, 506, 1375, 4631, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1654, 8386, 2996, 12, 3890, 1578, 2478, 16, 1758, 2236, 13, 3903, 5024, 288, 203, 3639, 2583, 12, 4631, 422, 389, 3576, 12021, 9334, 315, 16541, 30, 848, 1338, 1654, 8386, 4900, 364, 365, 8863, 203, 203, 3639, 389, 9083, 3056, 2996, 12, 4615, 16, 2236, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0x0c3E05F376130df7d0235c1df50333Ea0d837A94/sources/TCORE.sol
* @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`./ Addressing a broken checker contract
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"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "BEP20: transfer amount exceeds balance" ); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); if(feeDistributor != address(0)){ ITcoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); } } }
11,425,321
[ 1, 19297, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 353, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 15330, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 5267, 310, 279, 12933, 12489, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 5948, 52, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 5948, 52, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 389, 70, 26488, 63, 15330, 65, 273, 389, 70, 26488, 63, 15330, 8009, 1717, 12, 203, 5411, 3844, 16, 203, 5411, 315, 5948, 52, 3462, 30, 7412, 3844, 14399, 11013, 6, 203, 3639, 11272, 203, 203, 3639, 261, 11890, 5034, 7412, 774, 6275, 16, 2254, 5034, 7412, 774, 14667, 1669, 19293, 6275, 13, 273, 11083, 1340, 12053, 502, 12, 13866, 8847, 1887, 2934, 11162, 6275, 87, 4436, 14667, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 203, 3639, 2583, 12, 13866, 774, 6275, 18, 1289, 12, 13866, 774, 14667, 1669, 19293, 6275, 13, 422, 3844, 16, 315, 10477, 324, 6822, 16, 1552, 26189, 4859, 1440, 7225, 1769, 203, 203, 3639, 389, 70, 26488, 63, 20367, 65, 273, 389, 70, 26488, 63, 20367, 8009, 1289, 12, 13866, 774, 6275, 1769, 203, 3639, 3626, 12279, 12, 15330, 16, 8027, 16, 7412, 774, 6275, 1769, 203, 203, 3639, 309, 12, 13866, 774, 14667, 1669, 19293, 6275, 405, 374, 597, 14036, 1669, 19293, 480, 1758, 12, 20, 3719, 95, 203, 2 ]
pragma solidity ^0.4.24; /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcShort { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } contract modularFast is F3Devents {} contract FoMo3DFast is modularFast { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x27D5C0C175C1Ba67986319ac297d2F4D3bC2b7b2); address private admin = msg.sender; bool public activated_ = false; string constant public name = "FOMO Test"; string constant public symbol = "Test"; uint256 private rndExtra_ = 30 minutes; // length of the very first ICO uint256 private rndGap_ = 30 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 20 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 8 hours; // max length a round timer can be uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXnameQR(address _realSender,bytes32 _affCode, uint256 _team) isActivated() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePIDQR(_realSender,_eventData_); // fetch player id uint256 _pID = pIDxAddr_[_realSender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCoreQR(_realSender, _pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdrawQR(address _realSender) isActivated() payable public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[_realSender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( _realSender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, _realSender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ // function registerNameXID(string _nameString, uint256 _affCode, bool _all) // isHuman() // public // payable // { // bytes32 _name = _nameString.nameFilter(); // address _addr = msg.sender; // uint256 _paid = msg.value; // (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); // uint256 _pID = pIDxAddr_[_addr]; // // fire event // emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); // } // function registerNameXaddr(string _nameString, address _affCode, bool _all) // isHuman() // public // payable // { // bytes32 _name = _nameString.nameFilter(); // address _addr = msg.sender; // uint256 _paid = msg.value; // (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); // uint256 _pID = pIDxAddr_[_addr]; // // fire event // emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); // } // function registerNameXname(string _nameString, bytes32 _affCode, bool _all) // isHuman() // public // payable // { // bytes32 _name = _nameString.nameFilter(); // address _addr = msg.sender; // uint256 _paid = msg.value; // (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); // uint256 _pID = pIDxAddr_[_addr]; // // fire event // emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); // } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCoreQR(address _realSender,uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core coreQR(_realSender,_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( _realSender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 400000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 4000000000000000000) { uint256 _availableLimit = (4000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function coreQR(address _realSender,uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 400000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 4000000000000000000) { uint256 _availableLimit = (4000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTxQR(_realSender,_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePIDQR(address _realSender, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[_realSender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(_realSender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[_realSender] = _pID; plyr_[_pID].addr = _realSender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards admin.transfer(_com); admin.transfer(_p3d); //admin.transfer(_p3d.sub(_p3d / 2)); //round_[_rID].pot = _pot.add(_p3d / 2); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 3% out to community rewards uint256 _p1 = _eth / 100; uint256 _com = _eth / 50; _com = _com.add(_p1); uint256 _p3d; if (!address(admin).call.value(_com)()) { // This ensures Team Just cannot influence the outcome of FoMo3D with // bank migrations by breaking outgoing transactions. // Something we would never do. But that's not the point. // We spent 2000$ in eth re-deploying just to patch this, we hold the // highest belief that everything we create should be trustless. // Team JUST, The name you shouldn't have to trust. _p3d = _com; _com = 0; } // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract //uint256 _potAmount = _p3d / 2; admin.transfer(_p3d); //round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTxQR(address _realSender,uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, _realSender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } }
set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function buyXnameQR(address _realSender,bytes32 _affCode, uint256 _team) isActivated() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePIDQR(_realSender,_eventData_); uint256 _pID = pIDxAddr_[_realSender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } }
6,053,206
[ 1, 542, 731, 3134, 2229, 871, 501, 471, 4199, 309, 7291, 353, 394, 578, 486, 2158, 7291, 612, 10680, 7103, 330, 3840, 29252, 309, 1158, 7103, 330, 3840, 981, 1703, 864, 578, 7291, 12928, 358, 999, 3675, 4953, 16, 328, 355, 94, 999, 1142, 4041, 7103, 330, 3840, 981, 309, 7103, 330, 3840, 981, 1703, 864, 336, 7103, 330, 3840, 1599, 628, 7103, 3356, 309, 7103, 734, 353, 486, 326, 1967, 487, 7243, 4041, 1089, 1142, 7103, 330, 3840, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 30143, 60, 529, 29853, 12, 2867, 389, 7688, 12021, 16, 3890, 1578, 389, 7329, 1085, 16, 2254, 5034, 389, 10035, 13, 203, 1850, 353, 28724, 1435, 203, 1850, 353, 18949, 12768, 12, 3576, 18, 1132, 13, 203, 1850, 1071, 203, 1850, 8843, 429, 203, 1377, 288, 203, 1850, 478, 23, 40, 21125, 18, 1133, 1356, 3778, 389, 2575, 751, 67, 273, 4199, 16522, 29853, 24899, 7688, 12021, 16, 67, 2575, 751, 67, 1769, 203, 203, 1850, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 67, 7688, 12021, 15533, 203, 203, 1850, 2254, 5034, 389, 7329, 734, 31, 203, 1850, 309, 261, 67, 7329, 1085, 422, 875, 747, 389, 7329, 1085, 422, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 529, 13, 203, 1850, 288, 203, 2868, 389, 7329, 734, 273, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 31, 203, 203, 2868, 389, 7329, 734, 273, 293, 734, 92, 461, 67, 63, 67, 7329, 1085, 15533, 203, 203, 2868, 309, 261, 67, 7329, 734, 480, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 13, 203, 2868, 288, 203, 5375, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 389, 7329, 734, 31, 203, 2868, 289, 203, 1850, 289, 203, 203, 203, 1377, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract Locker { // create new type for states of the contract enum State {RUNNING, WAITING_FOR_CONFIRMATION, READY_TO_PAYOUT, COMPLETE} // variable to track the current state of the contract State public currState; bool public confirmedByPledgee; bool public confirmedBySupporter; //how much the pledgee has initialle locked uint public initialInvestment; //how much the supporters have added to the initialInvestment uint public supporterInvestment; //time until the contract returns uint256 public contractEndTime; //this is the guy that has a goal, confirms achievment and locks his funds address payable public pledgee; //this is the guy that confirms that the achievement is true, //raises the amount of funds in the contract //and receives a portion of the total funds in the end address payable public supporter; //only the Pledgee can call functions containing this modifier modifier onlyPledgee(){ require(msg.sender == pledgee, "Only Pledgee can call this method"); _; } //only the Pledgee can call functions containing this modifier, e.g. confirming the achiement modifier onlySupporter(){ require(msg.sender == supporter, "Only Supporter can call this method"); _; } //only the Pledgee OR Supporter can call functions containing this modifier, e.g. confirming the achiement modifier onlySupporterOrPledgee(){ require(msg.sender == pledgee, "Only Pledgee or Supporter can call this method"); _; require(msg.sender == supporter, "Only Pledgee or Supporter can call this method"); _; } constructor(address payable _pledgee, address payable _supporter, uint256 _contractEndTime) payable public { pledgee = _pledgee; supporter = _supporter; contractEndTime = _contractEndTime; initialInvestment = msg.value; currState = State.RUNNING; } //pledgee and supporter can confirm that goal is reached function confirmReachedGoal() onlySupporterOrPledgee external{ require(currState == State.WAITING_FOR_CONFIRMATION, "Endtime not reached yet. Please wait until contract ends."); if (msg.sender == pledgee && confirmedByPledgee == false){ confirmedByPledgee = true; } else if (msg.sender == supporter && confirmedBySupporter == false){ confirmedBySupporter = true; } else{ revert("Either you have already confirmed or you are not the supporter or the pledgee!"); } } //event that is triggered when time is reached and both, pledgee and supporter, have confirmed //JUST FOR DEBUGGING! DELETE FOR PRODUCTION! Function to trigger the "WAITING_FOR_CONFIRMATION" state before end time is reached function setState() public returns(State) { currState = State.WAITING_FOR_CONFIRMATION; return currState; } }
only the Pledgee OR Supporter can call functions containing this modifier, e.g. confirming the achiement
modifier onlySupporterOrPledgee(){ require(msg.sender == pledgee, "Only Pledgee or Supporter can call this method"); _; require(msg.sender == supporter, "Only Pledgee or Supporter can call this method"); _; }
15,847,962
[ 1, 3700, 326, 453, 19998, 73, 4869, 3425, 7988, 848, 745, 4186, 4191, 333, 9606, 16, 425, 18, 75, 18, 6932, 310, 326, 279, 24010, 820, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 3088, 7988, 1162, 52, 19998, 73, 1435, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 293, 19998, 73, 16, 315, 3386, 453, 19998, 73, 225, 578, 3425, 7988, 848, 745, 333, 707, 8863, 203, 3639, 389, 31, 203, 540, 2583, 12, 3576, 18, 15330, 422, 1169, 7988, 16, 315, 3386, 453, 19998, 73, 225, 578, 3425, 7988, 848, 745, 333, 707, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; /// @title A library for operation of address array /// @author ["Rivtower Technologies <[email protected]>"] /// @notice Use prefix to import it /// @dev TODO more interface library AddressArray { /// @notice Remove the value of the address array /// @param _value The value of address to be removed /// @param _array The array to remove from /// @return true if successed, false otherwise function remove(address _value, address[] storage _array) internal returns (bool) { uint _index = index(_value, _array); // Not found if (_index >= _array.length) return false; // Move the last element to the index of array _array[_index] = _array[_array.length - 1]; // Also delete the last element delete _array[_array.length - 1]; _array.length--; return true; } /// @notice Get the index of the value in the array /// @param _value The value of address to be founded /// @param _array The array to find from /// @return The index if founded, length of array otherwise function index(address _value, address[] _array) internal pure returns (uint i) { // Find the index of the value in the array for (i = 0; i < _array.length; i++) { if (_value == _array[i]) return i; } } /// @notice Check if the value in the array /// @param _value The value of address to be checked /// @param _array The array to check from /// @return true if existed, false otherwise function exist(address _value, address[] _array) internal pure returns (bool) { // Have found the value in array for (uint i = 0; i < _array.length; i++) { if (_value == _array[i]) return true; } // Not in return false; } /// @notice Check the array of address is null: /// 1. the length is zero 2. all values of array are zero /// @param _array The array to check from /// @return true if is null, false otherwise function isNull(address[] _array) internal pure returns (bool) { if (_array.length == 0) return true; for (uint i = 0; i < _array.length; i++) { if (address(0x0) != _array[i]) return false; } return true; } }
@notice Check the array of address is null: 1. the length is zero 2. all values of array are zero @param _array The array to check from @return true if is null, false otherwise
function isNull(address[] _array) internal pure returns (bool) { if (_array.length == 0) return true; for (uint i = 0; i < _array.length; i++) { if (address(0x0) != _array[i]) return false; } return true; }
15,840,800
[ 1, 1564, 326, 526, 434, 1758, 353, 446, 30, 404, 18, 326, 769, 353, 3634, 576, 18, 777, 924, 434, 526, 854, 3634, 225, 389, 1126, 1021, 526, 358, 866, 628, 327, 638, 309, 353, 446, 16, 629, 3541, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7612, 12, 2867, 8526, 389, 1126, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 309, 261, 67, 1126, 18, 2469, 422, 374, 13, 203, 5411, 327, 638, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 1126, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 2867, 12, 20, 92, 20, 13, 480, 389, 1126, 63, 77, 5717, 203, 7734, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.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); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/IdleMcdBridge.sol pragma solidity 0.5.11; interface IIdleV1 { // _amount is the amount of idleSAI that one wants to burn function redeemIdleToken(uint256 _amount) external returns (uint256 tokensRedeemed); function balanceOf(address _account) external view returns (uint256); function bestToken() external view returns(address); function iToken() external view returns(address); function cToken() external view returns(address); function token() external view returns(address); function tokenPrice() external view returns (uint256); } // File: contracts/interfaces/IIToken.sol pragma solidity 0.5.11; interface IIToken { function mint( address _receiver, uint256 _depositAmount) external returns (uint256 _mintAmount); function burn( address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function loanTokenAddress() external view returns (address); function tokenPrice() external view returns (uint256); } // File: contracts/libraries/Utils.sol pragma solidity 0.5.11; // Should not forget to linkx library Utils { using Math for uint256; function balanceOrAmount(IERC20 _token, uint256 _amount) internal view returns(uint256) { if(address(_token) == address(0)) { return address(this).balance; } return _token.balanceOf(address(this)).min(_amount); // return 1 ether; } } // File: contracts/partials/PartialIdleV1.sol pragma solidity 0.5.11; library PartialIdleV1 { using SafeMath for uint256; function burn(address _idleTokenAddress, uint256 _amount) internal { IIdleV1 idleToken = IIdleV1(_idleTokenAddress); uint256 idleTokenAmount = Utils.balanceOrAmount(IERC20(_idleTokenAddress), _amount); uint256 expectedAmount = idleTokenAmount.mul(idleToken.tokenPrice()).div(10**18); idleToken.redeemIdleToken(idleTokenAmount); require(IERC20(idleToken.token()).balanceOf(address(this)) >= (expectedAmount - 1), "PartialIdleV1.burn: IDLE_MONEY_MARKET_NOT_LIQUID"); } function getUnderlying(address _idleTokenAddress) internal returns(address) { return IIdleV1(_idleTokenAddress).token(); } } // File: contracts/interfaces/IIdleV2.sol pragma solidity 0.5.11; interface IIdleV2 { // one should approve the contract as spender for DAI before calling this method // _amount is the amount of SAI/DAI that one wants to lend // _clientProtocolAmounts can be an empty array for the migration function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts) external returns (uint256 mintedTokens); function token() external view returns(address); } // File: contracts/partials/PartialIdleV2.sol pragma solidity 0.5.11; library PartialIdleV2 { function mint(address _idleTokenAddress, uint256 _amount, uint256[] memory _clientProtocolAmounts) internal { IIdleV2 idleToken = IIdleV2(_idleTokenAddress); IERC20 token = IERC20(idleToken.token()); uint256 amount = Utils.balanceOrAmount(token, _amount); token.approve(_idleTokenAddress, amount); idleToken.mintIdleToken(amount, _clientProtocolAmounts); require(IERC20(_idleTokenAddress).transfer(msg.sender, IERC20(_idleTokenAddress).balanceOf(address(this))), 'Err transfering'); } function getUnderlying(address _idleTokenAddress) internal returns(address) { return IIdleV2(_idleTokenAddress).token(); } } // File: contracts/interfaces/IScdMcdMigration.sol pragma solidity 0.5.11; interface IScdMcdMigration { function swapSaiToDai(uint256 _amount) external; function swapDaiToSai(uint256 _amount) external; } // File: contracts/Registry.sol pragma solidity 0.5.11; contract Registry is Ownable { mapping(bytes32 => address) internal contracts; function lookup(bytes32 _hashedName) external view returns(address) { return contracts[_hashedName]; } function lookup(string memory _name) public view returns(address){ return contracts[keccak256(abi.encodePacked(_name))]; } function setContract(string memory _name, address _contractAddress) public { setContract(keccak256(abi.encodePacked(_name)), _contractAddress); } function setContract(bytes32 _hashedName, address _contractAddress) public onlyOwner { contracts[_hashedName] = _contractAddress; } } // File: contracts/libraries/RL.sol pragma solidity 0.5.11; library RL { // Mainnet Registry constant internal registry = Registry(0xDc7eB6c5d66e4816E5CC69a70AA22f4584167333); // Kovan /* Registry constant internal registry = Registry(0xECbA2158241a05B833F61F8BB56F690A63fBFF77); */ // keccakc256(abi.encodePacked("sai")); bytes32 public constant _sai = 0x121766960ca66154cf52cc7f62663f2342706e7901d35f1d93fb4a7c321fa14a; bytes32 public constant _dai = 0x9f08c71555a1be56230b2e2579fafe4777867e0a1b947f01073e934471de15c1; bytes32 public constant _daiMigrationContract = 0x42d07b69ad62387b020b27e811fc060bc382308c513cb96f08ea805c77a04f9b; bytes32 public constant _cache = 0x422c51ed3da5a7658c50a3684c705b5f1e3d2d1673c5e16aaf93ea6271bb54cf; bytes32 public constant _gateKeeper = 0xcfa0d7a8bc1be8e2b981746eace0929cdd2721f615b63382540820f02696577b; bytes32 public constant _treasury = 0xcbd818ad4dd6f1ff9338c2bb62480241424dd9a65f9f3284101a01cd099ad8ac; bytes32 public constant _kyber = 0x758760f431d5bf0c2e6f8c11dbc38ddba93c5ba4e9b5425f4730333b3ecaf21b; bytes32 public constant _synthetix = 0x52da455363ee608ccf172b43cb25e66cd1734a315508cf1dae3e995e8106011a; bytes32 public constant _synthetixDepot = 0xcfead29a36d4ab9b4a23124bdd16cdd5acfdf5334caa9b0df48b01a0b6d68b20; function lookup(bytes32 _hashedName) internal view returns(address) { return registry.lookup(_hashedName); } function dai() internal pure returns(bytes32) { return _dai; } function sai() internal pure returns(bytes32) { return _sai; } function daiMigrationContract() internal pure returns(bytes32) { return _daiMigrationContract; } function cache() internal pure returns(bytes32) { return _cache; } function gateKeeper() internal pure returns(bytes32) { return _gateKeeper; } function treasury() internal pure returns(bytes32) { return _treasury; } function kyber() internal pure returns(bytes32) { return _kyber; } function synthetix() internal pure returns(bytes32) { return _synthetix; } function synthetixDepot() internal pure returns(bytes32) { return _synthetixDepot; } } // File: contracts/partials/PartialMcdMigration.sol pragma solidity 0.5.11; library PartialMcdMigration { function swapSaiToDai(uint256 _amount) internal { IERC20 sai = IERC20(RL.lookup(RL.sai())); IScdMcdMigration daiMigrationContract = IScdMcdMigration(RL.lookup(RL.daiMigrationContract())); uint256 amount = Utils.balanceOrAmount(sai, _amount); sai.approve(address(daiMigrationContract), amount); daiMigrationContract.swapSaiToDai(amount); } function swapDaiToSai(uint256 _amount) internal { IERC20 dai = IERC20(RL.lookup(RL.dai())); IScdMcdMigration daiMigrationContract = IScdMcdMigration(RL.lookup(RL.daiMigrationContract())); uint256 amount = Utils.balanceOrAmount(dai, _amount); dai.approve(address(daiMigrationContract), amount); daiMigrationContract.swapDaiToSai(amount); } } // File: contracts/partials/PartialPull.sol pragma solidity 0.5.11; library PartialPull { using Math for uint256; function pull(IERC20 _token, uint256 _amount) internal { if(address(_token) == address(0)) { require(msg.value == _amount, "PartialPull.pull: MSG_VALUE_INCORRECT"); } // uint256 amount = Utils.balanceOrAmount(_token, _amount); // Either pull the balance, allowance or _amount, whichever is the smallest number uint256 amount = _token.balanceOf(msg.sender).min(_amount).min(_token.allowance(msg.sender, address(this))); require(_token.transferFrom(msg.sender, address(this), amount), "PartialPull.pull: TRANSFER_FAILED"); } } // File: contracts/partials/PartialPush.sol pragma solidity 0.5.11; library PartialPush { using Math for uint256; using Address for address; function push(IERC20 _token, address _receiver, uint256 _amount) internal { uint256 amount = Utils.balanceOrAmount(_token, _amount); if(address(_token) == address(0)) { _receiver.toPayable().transfer(amount); } _token.transfer(_receiver, amount); } } // File: contracts/TokenSaver.sol pragma solidity 0.5.11; contract TokenSaver is Ownable { function saveEther() external onlyOwner { msg.sender.transfer(address(this).balance); } function saveTokens(address _token) external onlyOwner { IERC20 token = IERC20(_token); // Some tokens do not allow a balance to drop to zero so we leave 1 wei to be safe token.transfer(msg.sender, token.balanceOf(address(this)) - 1); } } // File: contracts/static-recipes/IdleMcdBridge.sol pragma solidity 0.5.11; contract IdleMcdBridge is TokenSaver { uint256 constant MAX = uint256(-1); address public SAI; address public DAI; constructor(address _SAI, address _DAI) public { SAI = _SAI; DAI = _DAI; } function bridgeIdleV1ToIdleV2(address _V1, address _V2, uint256 _amount, uint256[] calldata _clientProtocolAmounts) external { PartialPull.pull(IERC20(_V1), _amount); PartialIdleV1.burn(_V1, _amount); address underlyingV1 = PartialIdleV1.getUnderlying(_V1); address underlyingV2 = PartialIdleV2.getUnderlying(_V2); if(underlyingV1 == SAI && underlyingV2 == DAI) { // Migrate SAI TO DAI PartialMcdMigration.swapSaiToDai(MAX); } else if(underlyingV1 == DAI && underlyingV2 == SAI) { // Migrate DAI TO SAI PartialMcdMigration.swapDaiToSai(MAX); } // Else idle tokens have same underlying asset so do nothing // Mint v2 Tokens PartialIdleV2.mint(_V2, MAX, _clientProtocolAmounts); } }
_amount is the amount of idleSAI that one wants to burn
interface IIdleV1 { function redeemIdleToken(uint256 _amount) external returns (uint256 tokensRedeemed); function balanceOf(address _account) external view returns (uint256); function bestToken() external view returns(address); function iToken() external view returns(address); function cToken() external view returns(address); function token() external view returns(address); function tokenPrice() external view returns (uint256); }
12,556,507
[ 1, 67, 8949, 353, 326, 3844, 434, 12088, 5233, 45, 716, 1245, 14805, 358, 18305, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 13834, 58, 21, 288, 203, 565, 445, 283, 24903, 13834, 1345, 12, 11890, 5034, 389, 8949, 13, 3903, 1135, 261, 11890, 5034, 2430, 426, 24903, 329, 1769, 203, 565, 445, 11013, 951, 12, 2867, 389, 4631, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 3796, 1345, 1435, 3903, 1476, 1135, 12, 2867, 1769, 203, 565, 445, 277, 1345, 1435, 3903, 1476, 1135, 12, 2867, 1769, 203, 565, 445, 276, 1345, 1435, 3903, 1476, 1135, 12, 2867, 1769, 203, 565, 445, 1147, 1435, 3903, 1476, 1135, 12, 2867, 1769, 203, 565, 445, 1147, 5147, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; contract Scholarship { // Contract that allows a third party validator (like a school) to check // grades of student and release escrow funds from a sponsor in rounds. // Inspired by seed investing. We call it "Seed Scholarships." struct SeedFund { address sponsor; // The individual who seeds money. initializes to 0x0. address student; // The individual seeking funds. uint startTerm; // The start date of the seed rounds, ends the ability to contribute. bool completed; // The funding is complete. uint fundsRequest; // The amount the student needs. uint balance; // The amount in the contract that will be returned to sponsor if unclaimed. uint initial; // Initial round of funding (at beginning of term.) uint roundOne; // Round one of funding after first grade report. uint roundTwo; // Round two of funding after second grade report. uint roundThree; // Round three of funding after third grade report. uint timelock; // Time that must elapse between rounds. [NOT MVP] // [NOT MVP] mapping(uint => Round) rounds; } struct GradeReport { bool reportOne; uint gradeOne; bool reportTwo; uint gradeTwo; bool reportThree; uint gradeThree; } // [NOT MVP] struct Round { // bool complete; // true if round already happened. // uint funds; // Amount held for round. // } address school; // The third party (school.) Could !(will)! be an oracle in the future. uint[] grades = [0, 1, 2, 3, 4]; // 0 = F ... 4 = A (Think GPA) mapping(address => mapping(address => bool)) validatesFor; // Maps school // to student and returns true if that school validates for that student. // mapping(address => bool) seeded; // Returns true if student already seeded. // mapping(address => SeedFund[]) scholarship; mapping(address => SeedFund) seedFunds; // ONE PER STUDENT ATM. mapping(address => GradeReport) gradeReports; address[] students; function Scholarship( address _school) { school = _school; } function officiateStudent(address _student, uint _request) { if (msg.sender != school) throw; // Only school official can validate student. validatesFor[school][_student] = true; students.push(_student); SeedFund sf = seedFunds[_student]; sf.fundsRequest = _request; // Eventually the student will be able to do this themselves. } function getStatus(address _student) constant returns (bool, address, uint) { if (!validatesFor[school][_student]) throw; bool seeded; SeedFund sf = seedFunds[_student]; if(sf.balance != 0) seeded = true; address sponsor = sf.sponsor; uint funds = sf.fundsRequest; return(seeded, sponsor, funds); } function seed(address _student, uint _initial, uint _roundOne, uint _roundTwo, uint _roundThree) payable { SeedFund sf = seedFunds[_student]; if (sf.sponsor != 0x0) throw; // Throw if student is sponsored. if (now > sf.startTerm) throw; // Throw if student already started term. if (!validatesFor[school][_student]) throw; // Throw if student not validated. uint totalScholarshipFund = msg.value; if (_initial + _roundOne + _roundTwo + _roundThree != totalScholarshipFund) throw; // Math's wrong! sf.initial = _initial; sf.roundOne = _roundOne; sf.roundTwo = _roundTwo; sf.roundThree = _roundThree; sf.balance = totalScholarshipFund; } function reportGrade(address _student, uint _round, uint _grade) returns (bool) { // INCLUDE TIMELOCK BETWEEN ROUNDS TO PROTECT THE SPONSOR.. AKA IF THEY // NOTICE SOMETHING FISHY... THEY CAN LOCK FUNDS. [NOT MVP] if (msg.sender != school) throw; // In the future, this will call an oracle to // report grades but for now the school must manually report. if (!validatesFor[school][_student]) throw; uint grade = 88; for (var i = 0; i < grades.length; i++) { if (_grade == grades[i]) grade = _grade; } require(grade != 88); // Make sure school entered in valid grade number. GradeReport gr = gradeReports[_student]; if (_round == 1) require(!gr.reportOne); gr.gradeOne = grade; gr.reportOne = true; return true; if (_round == 2) require(!gr.reportTwo); gr.gradeTwo = grade; gr.reportTwo = true; return true; if (_round == 3) require(!gr.reportThree); gr.gradeThree = grade; gr. reportThree = true; return true; return false; } // All the logic contained within this one function so the student only has // to call `studentWithdrawal()` and if there's any money unlocked, they will // get sent it. function studentWithdrawal() { SeedFund memory sf; GradeReport memory gr; for (var i = 0; i < students.length; i++) { if (msg.sender == students[i]) { sf = seedFunds[students[i]]; gr = gradeReports[students[i]]; } } require(sf.balance != 0); // require that it's nonzero require(!sf.completed); uint amt; if (sf.initial != 0 && now > sf.startTerm) { amt = sf.initial; if (!msg.sender.send(amt)) throw; sf.balance -= amt; sf.initial = 0; } else if (sf.roundOne != 0) { require(gr.reportOne); amt = sf.roundOne * gr.gradeOne; if (!msg.sender.send(amt)) throw; sf.balance -= amt; sf.roundOne = 0; } else if (sf.roundTwo != 0) { require(gr.reportOne); amt = sf.roundTwo; if (!msg.sender.send(amt)) throw; sf.balance -= amt; sf.roundTwo = 0; } else if (sf.roundThree != 0) { require(gr.reportOne); amt = sf.roundThree; if (!msg.sender.send(amt)) throw; sf.balance -= amt; sf.roundThree = 0; sf.completed = true; } else throw; } function listStudents() constant returns (address[]) { return students; } } // The contract above is deployed per school.
Only school official can validate student.
if (msg.sender != school) throw;
12,594,518
[ 1, 3386, 18551, 1371, 3397, 22354, 848, 1954, 18110, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3576, 18, 15330, 480, 18551, 1371, 13, 604, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7132c10A5fDeb8236Be65F451c1973E26E8515EF/sources/contracts/sugartown/SugartownOrasNFT.sol
* @dev Overriden transferFrom function for operator filtering./
function transferFrom(address from, address to, uint256 tokenId) public override onlyAllowedOperator(from) { super.transferFrom(from, to, tokenId); }
3,072,399
[ 1, 22042, 17951, 7412, 1265, 445, 364, 3726, 11346, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 3849, 1338, 5042, 5592, 12, 2080, 13, 288, 203, 3639, 2240, 18, 13866, 1265, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]