file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; interface IJIngle { function transfer(address _to, uint256 _tokenId) external virtual; } /// @title A wrapped contract for CryptoJingles V0 and V1 contract WrappedJingle is ERC721URIStorage, Ownable { event Wrapped(uint256 indexed, uint256, address); event Unwrapped(uint256 indexed, uint256, address); using Counters for Counters.Counter; Counters.Counter private _tokenIds; enum Version { V0, V1 } uint256 constant public NUM_V0_JINGLES = 30; uint256 constant public NUM_V1_JINGLES = 47; struct OldToken { uint256 tokenId; bool isWrapped; } mapping (uint256 => mapping (address => OldToken)) public tokenMap; mapping (address => mapping(uint256 => uint256)) public unwrappedToWrappedId; string private baseURI = "https://cryptojingles.me/wrapped-jingles/"; string private _contractURI = "https://cryptojingles.me/metadata"; constructor() ERC721("WrappedJingle", "WJL") { // we need _tokenIds to start at 1 _tokenIds.increment(); } /// @notice Locks an old v0/v1 jingle and gives the user a wrapped jingle /// @dev User must approve the contract to withdraw the asset /// @param _tokenId Token id of the asset to be wrapped /// @param _version 0 - v0 version, 1 - v1 version function wrap(uint256 _tokenId, Version _version) public { address jingleContract = getJingleAddr(_version); address owner = IERC721(jingleContract).ownerOf(_tokenId); // check if v0 can wrap require(wrapCheck(_tokenId, _version), "Only old V0 and V1 jingles allowed"); // check if user is owner require(owner == msg.sender, "Not token owner"); // pull user jingle IERC721(jingleContract).transferFrom(msg.sender, address(this), _tokenId); uint256 wrappedTokenId = 0; if(unwrappedToWrappedId[jingleContract][_tokenId] > 0) { wrappedTokenId = unwrappedToWrappedId[jingleContract][_tokenId]; transferFrom(address(this), msg.sender, wrappedTokenId); } else { // mint wrapped wrappedTokenId = mintNewToken(); unwrappedToWrappedId[jingleContract][_tokenId] = wrappedTokenId; } tokenMap[wrappedTokenId][jingleContract] = OldToken({ tokenId: _tokenId, isWrapped: true }); emit Wrapped(wrappedTokenId, _tokenId, jingleContract); } /// @notice Unlocks an old v0/v1 jingle and burnes the users wrapped jingle /// @dev User must approve the contract to withdraw the asset /// @param _wrappedTokenId Token id of the wrapped jingle /// @param _version 0 - v0 version, 1 - v1 version function unwrap(uint256 _wrappedTokenId, Version _version) public { // check if user is owner address jingleContract = getJingleAddr(_version); address owner = ownerOf(_wrappedTokenId); require(owner == msg.sender, "Not token owner"); // pull user wrapped jingle transferFrom(msg.sender, address(this), _wrappedTokenId); OldToken memory tokenData = tokenMap[_wrappedTokenId][jingleContract]; require(tokenData.isWrapped, "Token not wrapped"); tokenData.isWrapped = false; tokenMap[_wrappedTokenId][jingleContract] = tokenData; // send token to caller IJIngle(jingleContract).transfer(msg.sender, tokenData.tokenId); emit Unwrapped(_wrappedTokenId, tokenData.tokenId, jingleContract); } function mintNewToken() internal returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); return newItemId; } function wrapCheck(uint256 _tokenId, Version _version) internal pure returns (bool) { if (_version == Version.V0) { if (_tokenId > NUM_V0_JINGLES) return false; } else if (_version == Version.V1) { if (_tokenId > NUM_V1_JINGLES) return false; } return true; } function getJingleAddr(Version _version) internal pure returns (address) { if (_version == Version.V0) { return 0x5AF7Af54E8Bc34b293e356ef11fffE51d6f9Ae78; } else { return 0x5B6660ca047Cc351BFEdCA4Fc864d0A88F551485; } } /////////////////// PUBLIC //////////////////////// function totalSupply() public view returns (uint256) { return _tokenIds.current(); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } function baseTokenURI() public view returns (string memory) { return baseURI; } function contractURI() public view returns (string memory) { return _contractURI; } function setTokenURI(uint256 _tokenId, string memory _newTokenURI) public onlyOwner { _setTokenURI(_tokenId, _newTokenURI); } function setBaseURI(string memory newBaseURI) public onlyOwner { baseURI = newBaseURI; } function setContractURI(string memory newContractURI) public onlyOwner { _contractURI = newContractURI; } }
@notice Unlocks an old v0/v1 jingle and burnes the users wrapped jingle @dev User must approve the contract to withdraw the asset @param _wrappedTokenId Token id of the wrapped jingle @param _version 0 - v0 version, 1 - v1 version check if user is owner pull user wrapped jingle send token to caller
function unwrap(uint256 _wrappedTokenId, Version _version) public { address jingleContract = getJingleAddr(_version); address owner = ownerOf(_wrappedTokenId); require(owner == msg.sender, "Not token owner"); transferFrom(msg.sender, address(this), _wrappedTokenId); OldToken memory tokenData = tokenMap[_wrappedTokenId][jingleContract]; require(tokenData.isWrapped, "Token not wrapped"); tokenData.isWrapped = false; tokenMap[_wrappedTokenId][jingleContract] = tokenData; IJIngle(jingleContract).transfer(msg.sender, tokenData.tokenId); emit Unwrapped(_wrappedTokenId, tokenData.tokenId, jingleContract); }
12,795,347
[ 1, 7087, 87, 392, 1592, 331, 20, 19, 90, 21, 525, 1714, 471, 18305, 281, 326, 3677, 5805, 525, 1714, 225, 2177, 1297, 6617, 537, 326, 6835, 358, 598, 9446, 326, 3310, 225, 389, 18704, 1345, 548, 3155, 612, 434, 326, 5805, 525, 1714, 225, 389, 1589, 374, 300, 331, 20, 1177, 16, 404, 300, 331, 21, 1177, 866, 309, 729, 353, 3410, 6892, 729, 5805, 525, 1714, 1366, 1147, 358, 4894, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 11014, 12, 11890, 5034, 389, 18704, 1345, 548, 16, 4049, 389, 1589, 13, 1071, 288, 203, 3639, 1758, 525, 1714, 8924, 273, 9285, 1714, 3178, 24899, 1589, 1769, 203, 3639, 1758, 3410, 273, 3410, 951, 24899, 18704, 1345, 548, 1769, 203, 203, 3639, 2583, 12, 8443, 422, 1234, 18, 15330, 16, 315, 1248, 1147, 3410, 8863, 203, 540, 203, 3639, 7412, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 18704, 1345, 548, 1769, 203, 203, 3639, 18613, 1345, 3778, 1147, 751, 273, 1147, 863, 63, 67, 18704, 1345, 548, 6362, 78, 1714, 8924, 15533, 203, 203, 3639, 2583, 12, 2316, 751, 18, 291, 17665, 16, 315, 1345, 486, 5805, 8863, 203, 203, 3639, 1147, 751, 18, 291, 17665, 273, 629, 31, 203, 3639, 1147, 863, 63, 67, 18704, 1345, 548, 6362, 78, 1714, 8924, 65, 273, 1147, 751, 31, 203, 203, 3639, 467, 46, 382, 3213, 12, 78, 1714, 8924, 2934, 13866, 12, 3576, 18, 15330, 16, 1147, 751, 18, 2316, 548, 1769, 203, 203, 3639, 3626, 1351, 18704, 24899, 18704, 1345, 548, 16, 1147, 751, 18, 2316, 548, 16, 525, 1714, 8924, 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 ]
./full_match/1/0xdc2F3feD14a87ccE44440ceF069B3F17a868d929/sources/browser/Unibase.sol
* @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 { uint256 amt = amount; require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amt); _balances[account] = _balances[account].add(amt); emit Transfer(address(0), account, amt); }
2,908,749
[ 1, 2729, 1375, 8949, 68, 2430, 471, 22698, 2182, 358, 1375, 4631, 9191, 21006, 326, 2078, 14467, 7377, 1282, 279, 288, 5912, 97, 871, 598, 1375, 2080, 68, 444, 358, 326, 3634, 1758, 18, 29076, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 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, 565, 445, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 2254, 5034, 25123, 273, 3844, 31, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 3639, 389, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1289, 12, 301, 88, 1769, 203, 3639, 389, 70, 26488, 63, 4631, 65, 273, 389, 70, 26488, 63, 4631, 8009, 1289, 12, 301, 88, 1769, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 2236, 16, 25123, 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 ]
pragma solidity ^0.5.17; library SafeMath { function ADD171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB705(a, b, "SafeMath: subtraction overflow"); } function SUB705(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 MUL180(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 DIV369(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV369(a, b, "SafeMath: division by zero"); } function DIV369(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 MOD90(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD90(a, b, "SafeMath: modulo by zero"); } function MOD90(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } interface IERC20 { function TRANSFER190(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE617(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM76(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY562() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF573(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE952(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER195(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL248(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract MatrixErc20 { using SafeMath for uint; address public ownerWallet; struct UserStruct { bool isExist; uint id; mapping (address => uint256) tokenRewards; mapping (address => uint) referrerID; //Token address to Referrer ID mapping (address => address[]) referral; //Token address to list of addresses mapping(address => mapping(uint => uint)) levelExpired; //Token address to level number to expiration date } uint REFERRER_1_LEVEL_LIMIT = 5; uint PERIOD_LENGTH = 180 days; uint ADMIN_FEE_PERCENTAGE = 10; mapping(address => mapping(uint => uint)) public LEVEL_PRICE; //Token address to level number to price mapping (address => UserStruct) public users; mapping (uint => address) public userList; uint public currUserID = 0; mapping (address => bool) public tokens; mapping (address => uint256) public ownerFees; event REGLEVELEVENT510(address indexed _user, address indexed _referrer, uint _time, address _token); //inject NONSTANDARD NAMING event BUYLEVELEVENT399(address indexed _user, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING event PROLONGATELEVELEVENT866(address indexed _user, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING event GETMONEYFORLEVELEVENT355(address indexed _user, address indexed _referral, uint _level, address _token); //inject NONSTANDARD NAMING event LOSTMONEYFORLEVELEVENT103(address indexed _user, address indexed _referral, uint _level, uint _time, address _token); //inject NONSTANDARD NAMING function SETPERIODLENGTH571(uint _periodLength) public ONLYOWNER423 { //inject NONSTANDARD NAMING PERIOD_LENGTH = _periodLength; } function SETADMINFEEPERCENTAGE408(uint _adminFeePercentage) public ONLYOWNER423 { //inject NONSTANDARD NAMING require (_adminFeePercentage >= 0 && _adminFeePercentage <= 100, "Fee must be between 0 and 100"); ADMIN_FEE_PERCENTAGE = _adminFeePercentage; } function TOGGLETOKEN328(address _token, bool _enabled) public ONLYOWNER423 { //inject NONSTANDARD NAMING tokens[_token] = _enabled; if (_enabled) { for(uint i = 1; i <= 10; i++) { users[ownerWallet].levelExpired[_token][i] = 55555555555; } users[ownerWallet].referrerID[_token] = 0; } } function SETTOKENPRICEATLEVEL23(address _token, uint _level, uint _price) public ONLYOWNER423 { //inject NONSTANDARD NAMING require(_level > 0 && _level <= 10, "Invalid level"); LEVEL_PRICE[_token][_level] = _price; } function SETTOKENPRICE69(address _token, uint _price1, uint _price2, uint _price3, uint _price4, uint _price5, uint _price6, uint _price7, uint _price8, uint _price9, uint _price10) public ONLYOWNER423 { //inject NONSTANDARD NAMING LEVEL_PRICE[_token][1] = _price1; LEVEL_PRICE[_token][2] = _price2; LEVEL_PRICE[_token][3] = _price3; LEVEL_PRICE[_token][4] = _price4; LEVEL_PRICE[_token][5] = _price5; LEVEL_PRICE[_token][6] = _price6; LEVEL_PRICE[_token][7] = _price7; LEVEL_PRICE[_token][8] = _price8; LEVEL_PRICE[_token][9] = _price9; LEVEL_PRICE[_token][10] = _price10; if (!tokens[_token]) { TOGGLETOKEN328(_token, true); } } constructor() public { ownerWallet = msg.sender; UserStruct memory userStruct; currUserID++; userStruct = UserStruct({ isExist: true, id: currUserID }); users[ownerWallet] = userStruct; userList[currUserID] = ownerWallet; } modifier ONLYOWNER423() { //inject NONSTANDARD NAMING require(msg.sender == ownerWallet, 'caller must be the owner'); _; } //Use this before going live to avoid issues function TRANSFEROWNERSHIP988(address newOwner) public ONLYOWNER423 { //inject NONSTANDARD NAMING require(newOwner != address(0), 'new owner is the zero address'); require(!users[newOwner].isExist, 'new owner needs to be a new address'); UserStruct memory userStruct = UserStruct({ isExist: true, id: 1 }); users[newOwner] = userStruct; userList[1] = newOwner; delete users[ownerWallet]; ownerWallet = newOwner; } function REGUSER700(address _token, uint _referrerID) public payable { //inject NONSTANDARD NAMING require(tokens[_token], "Token is not enabled"); require(!users[msg.sender].isExist, 'User exist'); require(_referrerID > 0 && _referrerID <= currUserID, 'Incorrect referrer Id'); IERC20 token = IERC20(_token); require(token.TRANSFERFROM76(msg.sender, address(this), LEVEL_PRICE[_token][1]), "Couldn't take the tokens from the sender"); if(users[userList[_referrerID]].referral[_token].length >= REFERRER_1_LEVEL_LIMIT) _referrerID = users[FINDFREEREFERRER993(_token, userList[_referrerID])].id; UserStruct memory userStruct; currUserID++; userStruct = UserStruct({ isExist: true, id: currUserID }); users[msg.sender] = userStruct; users[msg.sender].referrerID[_token] = _referrerID; userList[currUserID] = msg.sender; users[msg.sender].levelExpired[_token][1] = now + PERIOD_LENGTH; users[userList[_referrerID]].referral[_token].push(msg.sender); PAYFORLEVEL516(_token, 1, msg.sender); emit REGLEVELEVENT510(msg.sender, userList[_referrerID], now, _token); } function BUYLEVEL817(address _token, uint _level) public payable { //inject NONSTANDARD NAMING require(users[msg.sender].isExist, 'User not exist'); require(_level > 0 && _level <= 10, 'Incorrect level'); require(tokens[_token], "Token is not enabled"); IERC20 token = IERC20(_token); require(token.TRANSFERFROM76(msg.sender, address(this), LEVEL_PRICE[_token][_level]), "Couldn't take the tokens from the sender"); if(_level == 1) { users[msg.sender].levelExpired[_token][1] += PERIOD_LENGTH; } else { for(uint l =_level - 1; l > 0; l--) require(users[msg.sender].levelExpired[_token][l] >= now, 'Buy the previous level'); if(users[msg.sender].levelExpired[_token][_level] == 0) users[msg.sender].levelExpired[_token][_level] = now + PERIOD_LENGTH; else users[msg.sender].levelExpired[_token][_level] += PERIOD_LENGTH; } PAYFORLEVEL516(_token, _level, msg.sender); emit BUYLEVELEVENT399(msg.sender, _level, now, _token); } function GETREFERERINTREE743(address _token, uint _level, address _user) internal view returns(address) { //inject NONSTANDARD NAMING address referer; address referer1; address referer2; address referer3; address referer4; if(_level == 1 || _level == 6) { referer = userList[users[_user].referrerID[_token]]; } else if(_level == 2 || _level == 7) { referer1 = userList[users[_user].referrerID[_token]]; referer = userList[users[referer1].referrerID[_token]]; } else if(_level == 3 || _level == 8) { referer1 = userList[users[_user].referrerID[_token]]; referer2 = userList[users[referer1].referrerID[_token]]; referer = userList[users[referer2].referrerID[_token]]; } else if(_level == 4 || _level == 9) { referer1 = userList[users[_user].referrerID[_token]]; referer2 = userList[users[referer1].referrerID[_token]]; referer3 = userList[users[referer2].referrerID[_token]]; referer = userList[users[referer3].referrerID[_token]]; } else if(_level == 5 || _level == 10) { referer1 = userList[users[_user].referrerID[_token]]; referer2 = userList[users[referer1].referrerID[_token]]; referer3 = userList[users[referer2].referrerID[_token]]; referer4 = userList[users[referer3].referrerID[_token]]; referer = userList[users[referer4].referrerID[_token]]; } if(!users[referer].isExist) referer = userList[1]; return referer; } function PAYFORLEVEL516(address _token, uint _level, address _user) internal { //inject NONSTANDARD NAMING address referer = GETREFERERINTREE743(_token, _level, _user); if(users[referer].levelExpired[_token][_level] >= now) { uint levelPrice = LEVEL_PRICE[_token][_level]; uint payToOwner = levelPrice.MUL180(ADMIN_FEE_PERCENTAGE).DIV369(100); uint payToReferrer = levelPrice.SUB705(payToOwner); users[address(uint160(referer))].tokenRewards[_token] = users[address(uint160(referer))].tokenRewards[_token].ADD171(payToReferrer); ownerFees[_token] = ownerFees[_token].ADD171(payToOwner); emit GETMONEYFORLEVELEVENT355(referer, msg.sender, _level, _token); } else { emit LOSTMONEYFORLEVELEVENT103(referer, msg.sender, _level, now, _token); PAYFORLEVEL516(_token, _level, referer); } } function FINDFREEREFERRER993(address _token, address _user) public view returns(address) { //inject NONSTANDARD NAMING if(users[_user].referral[_token].length < REFERRER_1_LEVEL_LIMIT) return _user; address[] memory referrals = new address[](315); referrals[0] = users[_user].referral[_token][0]; referrals[1] = users[_user].referral[_token][1]; referrals[2] = users[_user].referral[_token][2]; referrals[3] = users[_user].referral[_token][3]; referrals[4] = users[_user].referral[_token][4]; address freeReferrer; bool noFreeReferrer = true; for(uint i = 0; i < 126; i++) { if(users[referrals[i]].referral[_token].length == REFERRER_1_LEVEL_LIMIT) { if(i < 155) { referrals[(i+1)*2] = users[referrals[i]].referral[_token][0]; referrals[(i+1)*2+1] = users[referrals[i]].referral[_token][2]; referrals[(i+1)*2+2] = users[referrals[i]].referral[_token][3]; referrals[(i+1)*2+3] = users[referrals[i]].referral[_token][4]; referrals[(i+1)*2+4] = users[referrals[i]].referral[_token][5]; } } else { noFreeReferrer = false; freeReferrer = referrals[i]; break; } } require(!noFreeReferrer, 'No Free Referrer'); return freeReferrer; } function WITHDRAW913(address _token) public { //inject NONSTANDARD NAMING uint256 total = users[msg.sender].tokenRewards[_token]; require(total > 0, "Nothing to withdraw"); users[msg.sender].tokenRewards[_token] = 0; IERC20 token = IERC20(_token); require(token.TRANSFER190(msg.sender, total), "Couldn't send the tokens"); } function _WITHDRAWFEES891(address _token) public ONLYOWNER423 { //inject NONSTANDARD NAMING uint256 total = ownerFees[_token]; require(total > 0, "Nothing to withdraw"); ownerFees[_token] = 0; IERC20 token = IERC20(_token); require(token.TRANSFER190(msg.sender, total), "Couldn't send the tokens"); } function VIEWUSERREFERRAL790(address _token, address _user) public view returns(address[] memory) { //inject NONSTANDARD NAMING return users[_user].referral[_token]; } function VIEWUSERREFERRER85(address _token, address _user) public view returns(uint256) { //inject NONSTANDARD NAMING return users[_user].referrerID[_token]; } function VIEWUSERLEVELEXPIRED566(address _token, address _user, uint _level) public view returns(uint) { //inject NONSTANDARD NAMING return users[_user].levelExpired[_token][_level]; } function VIEWUSERISEXIST611(address _user) public view returns(bool) { //inject NONSTANDARD NAMING return users[_user].isExist; } function VIEWUSERREWARDS680(address _user, address _token) public view returns(uint256) { //inject NONSTANDARD NAMING return users[_user].tokenRewards[_token]; } function BYTESTOADDRESS886(bytes memory bys) private pure returns (address addr) { //inject NONSTANDARD NAMING assembly { addr := mload(add(bys, 20)) } } function _CLOSE871(address payable _to) public ONLYOWNER423 { //inject NONSTANDARD NAMING selfdestruct(_to); } }
inject NONSTANDARD NAMING
function VIEWUSERISEXIST611(address _user) public view returns(bool) {
15,849,282
[ 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, 21794, 4714, 45, 1090, 60, 5511, 26, 2499, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 12, 6430, 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 ]
./full_match/5/0x559385E8728b7d8C98B3910e5531D8C49F861c31/sources/project:/contracts/main/MentaportVerify.sol
* @dev Throws if called by any account other than a minter role/
modifier onlyMinter() { _checkMinter(); _; }
1,916,263
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 279, 1131, 387, 2478, 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 ]
[ 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, 9606, 1338, 49, 2761, 1435, 288, 203, 3639, 389, 1893, 49, 2761, 5621, 203, 3639, 389, 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, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> contract StarWarsRTscore is usingOraclize { /* Declaration */ address public OWNERS = 0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A; uint public constant COMMISSION = 0; // Commission for the owner uint public constant MIN_BET = 0.01 ether; uint public EXPECTED_START = 1523818800; // When the bet's event is expected to start uint public EXPECTED_END = 1527879600; // When the bet's event is expected to end uint public constant BETTING_OPENS = 1522998700; uint public BETTING_CLOSES = EXPECTED_START - 60; // Betting closes a minute before the bet event starts uint public constant PING_ORACLE_INTERVAL = 60 * 60 * 24; // Ping oracle every 24 hours until completion (or cancelation) uint public ORACLIZE_GAS = 200000; uint public CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; // Cancelation date is 24 hours after the expected end uint public RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; // Any leftover money is returned to owners 1 month after bet ends bool public completed; bool public canceled; bool public ownersPayed; uint public ownerPayout; bool public returnedToOwners; uint public winnerDeterminedDate; uint public numCollected = 0; bytes32 public nextScheduledQuery; uint public oraclizeFees; uint public collectionFees; struct Better { uint betAmount; uint betOption; bool withdrawn; } mapping(address => Better) betterInfo; address[] public betters; uint[2] public totalAmountsBet; uint[2] public numberOfBets; uint public totalBetAmount; uint public winningOption = 2; /* Events */ event BetMade(); /* Modifiers */ // Modifier to only allow the // determination of the winner modifier canDetermineWinner() { require (winningOption == 2 && !completed && !canceled && now > BETTING_CLOSES && now >= EXPECTED_END); _; } // Modifier to only allow emptying // the remaining value of the contract // to owners. modifier canEmptyRemainings() { require(canceled || completed); uint numRequiredToCollect = canceled ? (numberOfBets[0] + numberOfBets[1]) : numberOfBets[winningOption]; require ((now >= RETURN_DATE && !canceled) || (numCollected == numRequiredToCollect)); _; } // Modifier to only allow the collection // of bet payouts when winner is determined, // (or withdrawals if the bet is canceled) modifier collectionsEnabled() { require (canceled || (winningOption != 2 && completed && now > BETTING_CLOSES)); _; } // Modifier to only allow the execution of // owner payout when winner is determined modifier canPayOwners() { require (!canceled && winningOption != 2 && completed && !ownersPayed && now > BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions when betting is closed modifier bettingIsClosed() { require (now >= BETTING_CLOSES); _; } // Modifier to only allow the execution of // certain functions restricted to the owners modifier onlyOwnerLevel() { require( OWNERS == msg.sender ); _; } /* Functions */ // Constructor function StarWarsRTscore() public payable { oraclize_setCustomGasPrice(1000000000); callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for outcome } function changeGasLimitAndPrice(uint gas, uint price) public onlyOwnerLevel { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(price); } // Change bet expected times function setExpectedTimes(uint _EXPECTED_START, uint _EXPECTED_END) public onlyOwnerLevel { setExpectedStart(_EXPECTED_START); setExpectedEnd(_EXPECTED_END); } // Change bet expected start time function setExpectedStart(uint _EXPECTED_START) public onlyOwnerLevel { EXPECTED_START = _EXPECTED_START; BETTING_CLOSES = EXPECTED_START - 60; } // Change bet expected end time function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel { require(_EXPECTED_END > EXPECTED_START); EXPECTED_END = _EXPECTED_END; CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for winner } function callOracle(uint timeOrDelay, uint gas) private { require(canceled != true && completed != true); // Make a call to the oracle — // usually a script hosted on IPFS that // Oraclize deploys, after a given delay. We // leave nested query as default to maximize // optionality for queries. // To readers of the code (aka prospective betters) // if this is a computation query, you can view the // script we use to compute the winner, as it is hosted // on IPFS. The first argument in the computation query // is the IPFS hash (script would be located at // ipfs.io/ipfs/<HASH>). The file hosted at this hash // is actually a zipped folder that contains a Dockerfile and // the script. So, if you download the file at the hash provided, // ensure to convert it to a .zip, unzip it, and read the code. // Oraclize uses the Dockerfile to deploy this script. // Look over the Oraclize documentation to verify this // for yourself. nextScheduledQuery = makeOraclizeQuery(timeOrDelay, "nested", "[computation] ['QmVqSjNY64VfpnE3sZZZ7rv1uUpZRW9D8BXsbiNnwSGgmN', 'solo_a_star_wars_story']", gas); } function makeOraclizeQuery(uint timeOrDelay, string datasource, string query, uint gas) private returns(bytes32) { oraclizeFees += oraclize_getPrice(datasource, gas); return oraclize_query(timeOrDelay, datasource, query, gas); } // Determine the outcome manually, // immediately function determineWinner(uint gas, uint gasPrice) payable public onlyOwnerLevel canDetermineWinner { ORACLIZE_GAS = gas; oraclize_setCustomGasPrice(gasPrice); callOracle(0, ORACLIZE_GAS); } // Callback from Oraclize function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner { require(msg.sender == oraclize_cbAddress()); // The Oracle must always return // an integer (either 0 or 1, or if not then) // it should be 2 if (keccak256(result) != keccak256("0") && keccak256(result) != keccak256("1")) { // Reschedule winner determination, // unless we're past the point of // cancelation. If nextScheduledQuery is // not the current query, it means that // there's a scheduled future query, so // we can wait for that instead of scheduling // another one now (otherwise this would cause // dupe queries). if (now >= CANCELATION_DATE) { cancel(); } else if (nextScheduledQuery == queryId) { callOracle(PING_ORACLE_INTERVAL, ORACLIZE_GAS); } } else { setWinner(parseInt(result)); } } function setWinner(uint winner) private { completed = true; canceled = false; winningOption = winner; winnerDeterminedDate = now; payOwners(); } // Returns the total amounts betted // for the sender function getUserBet(address addr) public constant returns(uint[]) { uint[] memory bets = new uint[](2); bets[betterInfo[addr].betOption] = betterInfo[addr].betAmount; return bets; } // Returns whether a user has withdrawn // money or not. function userHasWithdrawn(address addr) public constant returns(bool) { return betterInfo[addr].withdrawn; } // Returns whether winning collections are // now available, or not. function collectionsAvailable() public constant returns(bool) { return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a hacker bets a lot to steal the entire losing pot, and hacks the oracle) } // Returns true if we can bet (in betting window) function canBet() public constant returns(bool) { return (now >= BETTING_OPENS && now < BETTING_CLOSES && !canceled && !completed); } // Function for user to bet on launch // outcome function bet(uint option) public payable { require(canBet() == true); require(msg.value >= MIN_BET); require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option); // Add better to better list if they // aren't already in it if (betterInfo[msg.sender].betAmount == 0) { betterInfo[msg.sender].betOption = option; numberOfBets[option]++; betters.push(msg.sender); } // Perform bet betterInfo[msg.sender].betAmount += msg.value; totalBetAmount += msg.value; totalAmountsBet[option] += msg.value; BetMade(); // Trigger event } // Empty remainder of the value in the // contract to the owners. function emptyRemainingsToOwners() private canEmptyRemainings { OWNERS.transfer(this.balance); returnedToOwners = true; } function returnToOwners() public onlyOwnerLevel canEmptyRemainings { emptyRemainingsToOwners(); } // Performs payout to owners function payOwners() private canPayOwners { if (COMMISSION == 0) { ownersPayed = true; ownerPayout = 0; collectionFees = ((oraclizeFees != 0) ? (oraclizeFees / numberOfBets[winningOption] + 1) : 0); // We add 1 wei to act as a ceil for the integer div -- important because the contract cannot afford to lose that spare change, as it will gaurantee that the final payout collection will fail. return; } // Calculate total pool of ETH // betted for the two outcomes. uint losingChunk = totalAmountsBet[1 - winningOption]; ownerPayout = (losingChunk - oraclizeFees) / COMMISSION; // Payout to the owner; commission of losing pot, minus the same % of the fees collectionFees = ((oraclizeFees != 0) ? ((oraclizeFees - oraclizeFees / COMMISSION) / numberOfBets[winningOption] + 1) : 0); // The fees to be distributed to the collectors, after owner payout. See reasoning above for adding the 1 wei. // Equal weight payout to the owners OWNERS.transfer(ownerPayout); ownersPayed = true; } function cancelBet() payable public onlyOwnerLevel { cancel(); } // Cancel bet and relase all the bets back to // the betters if, for any reason, payouts cannot be // completed. (For example Oracle fails.) Triggered by owners. function cancel() private { canceled = true; completed = false; } // Fallback function in case someone sends // ether to the contract so it doesn't get // lost. Could be used by us owners as buffer // value in case payouts fail. function() payable public { } // Function that lets betters collect their // money, either if the bet was canceled, // or if they won. function collect() public collectionsEnabled { address better = msg.sender; require(betterInfo[better].betAmount > 0); require(!betterInfo[better].withdrawn); require(canceled != completed); require(canceled || (completed && betterInfo[better].betOption == winningOption)); require(now >= (winnerDeterminedDate + 600)); uint payout = 0; if (!canceled) { // On top of their original bet, // add in profit, which is a weighted // proportion of the losing pot, relative // to their contribution to the winning pot, // minus owner commission. uint losingChunk = totalAmountsBet[1 - winningOption]; payout = betterInfo[better].betAmount + (betterInfo[better].betAmount * (losingChunk - ownerPayout) / totalAmountsBet[winningOption]) - collectionFees; } else { payout = betterInfo[better].betAmount; } if (payout > 0) { better.transfer(payout); betterInfo[better].withdrawn = true; numCollected++; } } }
When the bet's event is expected to end
uint public EXPECTED_END = 1527879600;
14,496,459
[ 1, 9434, 326, 2701, 1807, 871, 353, 2665, 358, 679, 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, 225, 2254, 1071, 5675, 23615, 67, 4415, 273, 4711, 5324, 28, 7235, 28133, 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/0x6c51041A91C91C86f3F08a72cB4D3F67f1208897/sources/src/modules/price-router/PriceRouter.sol
* @notice Attempted to edit an asset that is not supported./
error PriceRouter__AssetNotAdded(address asset);
5,008,663
[ 1, 28788, 358, 3874, 392, 3310, 716, 353, 486, 3260, 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 ]
[ 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, 555, 20137, 8259, 972, 6672, 1248, 8602, 12, 2867, 3310, 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, -100, -100 ]
pragma solidity >=0.4.21 <0.6.0; import "./ERC721Mintable.sol"; import "./verifier.sol"; // TODO define a contract call to the zokrates generated solidity contract <Verifier> or <renamedVerifier> // TODO define another contract named SolnSquareVerifier that inherits from your ERC721Mintable class contract SolnSquareVerifier is Verifier, RealEstateERC721Token { // TODO define a solutions struct that can hold an index & an address struct Solutions { uint256 tokenId; address owner; bool exists; } // TODO define an array of the above struct Solutions[] mintedTokens; // TODO define a mapping to store unique solutions submitted mapping(bytes32 => Solutions) private solutions; mapping (uint256 => Solutions) tokenIdToSolutions; // TODO Create an event to emit when a solution is added event SolutionAdded(uint256 indexed tokenId, address indexed owner); function getSolutionKey ( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input ) internal pure returns(bytes32) { return keccak256(abi.encodePacked(a, b, c, input)); } // TODO Create a function to add the solutions to the array and emit the event function addSolution ( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input, address to, uint256 tokenId ) public { mintedTokens.push(Solutions({ exists: true, tokenId: tokenId, owner: to })); // EMG - Register Solution bytes32 solutionKey = getSolutionKey(a, b, c, input); solutions[solutionKey] = Solutions({ exists: true, tokenId: tokenId, owner: to }); emit SolutionAdded(tokenId, to); } // TODO Create a function to mint new NFT only after the solution has been verified function mintNewNFT ( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input, address to, uint256 tokenId ) public returns (bool) { // Mint new NFT only after solution is verified bool verificationResult = Verifier.verifyTx(a, b, c, input); require(verificationResult, "The solution has not been successfully verified"); // Make sure solution is unique bytes32 solutionKey = getSolutionKey(a, b, c, input); require(!solutions[solutionKey].exists, "The solution has already been used"); // Handle metadata bool minted = super.mint(to, tokenId); require(minted, "Mint has not been successfully completed"); addSolution(a, b, c,input, to, tokenId); return true; } function solutionIsSubmitted ( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[2] memory input ) public view returns(bool) { bytes32 solutionKey = getSolutionKey(a,b, c, input); return (solutions[solutionKey].exists); } } // https://www.youtube.com/watch?v=0pY1Sd7aDjM&feature=youtu.be - used this video guide for the Zokrates implementation
TODO Create an event to emit when a solution is added
event SolutionAdded(uint256 indexed tokenId, address indexed owner);
919,126
[ 1, 6241, 1788, 392, 871, 358, 3626, 1347, 279, 6959, 353, 3096, 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, 29172, 8602, 12, 11890, 5034, 8808, 1147, 548, 16, 1758, 8808, 3410, 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 ]
./full_match/3/0xA7D4862d12371797dA656E97C0F3A090f1D11A15/sources/tam/vxx.sol
sets the balance of the Director to whatever it was plus the amount they are redeeming.
DInfo[_directoraddr].SponsorBalance = (DInfo[_directoraddr].SponsorBalance).add(_amount.mul(ratio));
14,244,971
[ 1, 4424, 326, 11013, 434, 326, 29701, 358, 15098, 518, 1703, 8737, 326, 3844, 2898, 854, 283, 24903, 310, 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 ]
[ 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, 5411, 463, 966, 63, 67, 7205, 280, 4793, 8009, 55, 500, 2467, 13937, 273, 261, 40, 966, 63, 67, 7205, 280, 4793, 8009, 55, 500, 2467, 13937, 2934, 1289, 24899, 8949, 18, 16411, 12, 9847, 10019, 540, 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 ]
./partial_match/4/0x0930739d6B2e54bdf01bAc1E08F9fc6cD59f897E/sources/PitayaBar.sol
PitayaBar is the coolest bar in town. You come in with some Pitaya, and leave with more! The longer you stay, the more Pitaya you get. This contract handles swapping to and from xPitaya, PitayaSwap's staking token. Define the Pitaya token contract
contract PitayaBar is ERC20("PitayaBar", "xPTY"){ using SafeMath for uint256; IUniswapV2ERC20 public pitaya; constructor(IUniswapV2ERC20 _pitaya) public { pitaya = _pitaya; } function enter(uint256 _amount) public { uint256 totalPitaya = pitaya.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalPitaya == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalPitaya); _mint(msg.sender, what); } } function enter(uint256 _amount) public { uint256 totalPitaya = pitaya.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalPitaya == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalPitaya); _mint(msg.sender, what); } } function enter(uint256 _amount) public { uint256 totalPitaya = pitaya.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalPitaya == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalPitaya); _mint(msg.sender, what); } } pitaya.transferFrom(msg.sender, address(this), _amount); function enterWithPermit(uint256 _amount, bool approveMax, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { pitaya.permit( msg.sender, address(this), approveMax ? uint256(-1) : _amount, deadline, v, r, s ); enter(_amount); } function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(pitaya.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); pitaya.transfer(msg.sender, what); } }
8,640,272
[ 1, 52, 305, 528, 69, 5190, 353, 326, 27367, 395, 4653, 316, 358, 91, 82, 18, 4554, 12404, 316, 598, 2690, 453, 305, 528, 69, 16, 471, 8851, 598, 1898, 5, 1021, 7144, 1846, 23449, 16, 326, 1898, 453, 305, 528, 69, 1846, 336, 18, 1220, 6835, 7372, 7720, 1382, 358, 471, 628, 619, 52, 305, 528, 69, 16, 453, 305, 528, 69, 12521, 1807, 384, 6159, 1147, 18, 13184, 326, 453, 305, 528, 69, 1147, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 453, 305, 528, 69, 5190, 353, 4232, 39, 3462, 2932, 52, 305, 528, 69, 5190, 3113, 315, 92, 6915, 7923, 95, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 467, 984, 291, 91, 438, 58, 22, 654, 39, 3462, 1071, 293, 305, 528, 69, 31, 203, 203, 203, 565, 3885, 12, 45, 984, 291, 91, 438, 58, 22, 654, 39, 3462, 389, 84, 305, 528, 69, 13, 1071, 288, 203, 3639, 293, 305, 528, 69, 273, 389, 84, 305, 528, 69, 31, 203, 565, 289, 203, 203, 565, 445, 6103, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2254, 5034, 2078, 52, 305, 528, 69, 273, 293, 305, 528, 69, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 24051, 273, 2078, 3088, 1283, 5621, 203, 3639, 309, 261, 4963, 24051, 422, 374, 747, 2078, 52, 305, 528, 69, 422, 374, 13, 288, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 3639, 289, 7010, 3639, 469, 288, 203, 5411, 2254, 5034, 4121, 273, 389, 8949, 18, 16411, 12, 4963, 24051, 2934, 2892, 12, 4963, 52, 305, 528, 69, 1769, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 4121, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 6103, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2254, 5034, 2078, 52, 305, 528, 69, 273, 293, 305, 528, 69, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; // HOOPS NFT // ________ // o | __ | // \_ O | |__| | // ____/ \ |___WW___| // __/ / || // || // || // _______________||________________ // Created by MasoRich and Bubba Dutch Studios // Contract by mö̵͊ö̵͊n & The Nexus Crew // Based on ERC721A contract by Chiru Labs contract Hoops is ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; string private _unrevealedBaseURI = 'ipfs://QmekCwrU6SsTNcFEgCs36kcry6KE7zeBsSuC1nXi5KZL6o/'; // ................ // ..... .... string private _baseURI = ''; // ... ..%%%%%%%%%%%%%%%. .... // .%. ..%%%%%..... .....%%%%%.. .. address _treasuryAddress = 0x87Bc1aC91E5BeC68BCe0427A0E627828F7c52a67; // .. .%%%... ..%%%. .. // .. .%%.. .%%. .. string private _uriSuffix = '.json'; // % .%%. WE <3 BASKETBALL .%% .. // . %%% .%% % uint private _mintPrice = 0.0824 ether; // % %%% HOOPS 4 LYFE %%% % // % %% %% % uint private _maxMintQuantity = 25; // % %% ssssssssssssss %% % // % %% %% %% %% % uint private _maxSupply = 10000; // % %% %% %% %% % // % %% %% %% %% % bool _mintIsOpen = false; // % %% %% %% %% % // % %% %% %% %% % uint private _revealIndex = 0; // % %% %% %% %% % // % %% .%%%%%%%%%%%%%%%%%%. %% % bool _stickersEnabled = false; // % %%% .%..%...%..%...%..%. %%% % // % %% .. % % % % % %% % uint256 internal currentIndex = 1; // % %%. %. %% % % % . .%% % // %. .%% %%%%%%%%%%%%%%%%% %%. % // Mapping from token ID to ownership details // %. .%%. % %% %% % %% % .%%. . mapping(uint256 => TokenOwnership) internal _ownerships; // .. .%%. .% % %% % %. % .%%. . // .. .%%%. %..%.....%..%..% ..%%. .. // Mapping owner address to address data // .. .%%..% %% %%% % %%.%%.. .. mapping(address => AddressData) private _addressData; // .. ..%% %. %%% %. %%%. ... // ... %%.%..%%..%%.% ... // Mapping from token ID to approved address // ... %%.%..%%..%.%% ... mapping(uint256 => address) private _tokenApprovals; // ..% % %% % %%. // % %% %% % % // %%%%%%%%%%%% // Mapping from owner to operator approvals // . % %% % % mapping(address => mapping(address => bool)) private _operatorApprovals;// % % %% % %. // %.%%.%.%.% // This the is owner of the contract address private _owner; // Stickers will be a customization option we enable after launch // Users should use the portal app we provide, although anyone can make customizations if they really want // Please use this feature responsibly so we don't have to turn it off for everyone or make it owner-only mapping(uint256 => string) internal _stickerURIs; // Should only the owner of the contract be able to customize the stickers? bool _anyoneCanCustomize = true; function setAnyoneCanCustomize(bool anyoneCanCustomize) public onlyOwner { _anyoneCanCustomize = anyoneCanCustomize; } function setStickersEnabled(bool stickersEnabled) public onlyOwner { _stickersEnabled = stickersEnabled; } function setStickerUri(uint256 tokenId, string memory uri) public { require((_anyoneCanCustomize && _stickersEnabled) || msg.sender == _owner, "Stickers are not customizable right now"); require(ownerOf(tokenId) == msg.sender || msg.sender == _owner, "Only the token owner can set the sticker URI"); _stickerURIs[tokenId] = uri; } function hasStickers(uint256 tokenId) public view returns (bool) { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); return bytes(_stickerURIs[tokenId]).length != 0; } function getStickerUri(uint256 tokenId) public view returns (string memory) { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); // TASK: return true if the sticker URI is set in _stickerURIs mapping and false if it is an empty string if(bytes(_stickerURIs[tokenId]).length > 0){ return _stickerURIs[tokenId]; } return ""; } function resetStickers(uint256 tokenId) public { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); require(ownerOf(tokenId) == msg.sender || msg.sender == _owner, "Only the owner can reset sticker uri"); _stickerURIs[tokenId] = ""; } struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _owner = msg.sender; } function getMintPrice() public view returns (uint) { return _mintPrice; } // Set the _mintPrice to a new value in ether if the msg.sender is the _owner function setMintPrice(uint newPrice) public onlyOwner { _mintPrice = newPrice; } function transferOwnership(address owner) public virtual onlyOwner { _owner = owner; } function withdraw() public onlyTreasurerOrOwner { // This will transfer the remaining contract balance to the owner. (bool os, ) = payable(_treasuryAddress).call{value: address(this).balance}(''); require(os); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, 'Caller is not the owner'); _; } /** * @dev Throws if called by any account other than the owner or treasurer. */ modifier onlyTreasurerOrOwner() { require(_owner == msg.sender || _owner == _treasuryAddress, 'Caller is not the owner or treasurer'); _; } modifier onlyValidAccess() { require(_owner == msg.sender || _mintIsOpen, 'You are not the owner and the mint is not open'); _; } function isMintOpen() public view returns (bool) { return _mintIsOpen; } function setOpenMint(bool mintIsOpen) public onlyOwner { _mintIsOpen = mintIsOpen; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex - 1; } function maxSupply() public view returns (uint256) { return _maxSupply; } function availableSupply() public view returns (uint256) { return _maxSupply - (currentIndex - 1); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < currentIndex && index > 0, 'Index must be between 1 and 10,000'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address tokenOwner, uint256 index) public view override returns (uint256) { require(index < balanceOf(tokenOwner), 'Owner index is out of bounds'); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i = 1; i < currentIndex; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == tokenOwner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('No token found'); // unable to get token of owner by index } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), '0x'); // balance query for the zero address return uint256(_addressData[owner].balance); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'No token found'); // owner query for nonexistent token unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('No owner'); // unable to determine the owner of token } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return 'Hoops'; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return 'HOOPS'; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'No token found'); // ERC721Metadata: URI query for nonexistent token if(_stickersEnabled && hasStickers(tokenId)){ return string(abi.encodePacked(_stickerURIs[tokenId], tokenId.toString(), _uriSuffix)); } return string(abi.encodePacked(tokenId < _revealIndex ? _baseURI : _unrevealedBaseURI, tokenId.toString(), _uriSuffix)); } /** * @dev This gets us the non-sticker URI, even if stickers are enabled */ function baseTokenURI(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), 'No token found'); // ERC721Metadata: URI query for nonexistent token return string(abi.encodePacked(tokenId < _revealIndex ? _baseURI : _unrevealedBaseURI, tokenId.toString(), _uriSuffix)); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setUnrevealBaseURI(string memory baseURI) public onlyOwner { _unrevealedBaseURI = baseURI; } function setRevealIndex(uint index) public onlyOwner { _revealIndex = index; } function setUriSuffix(string memory uriSuffix) public onlyOwner { _uriSuffix = uriSuffix; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = Hoops.ownerOf(tokenId); require(to != owner, 'Only the owner can call this function'); // approval to current owner require( msg.sender == owner || isApprovedForAll(owner, msg.sender), 'Not approved' // approve caller is not owner nor approved for all ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'No token found'); // approved query for nonexistent token return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != msg.sender, 'Not the caller'); // approve to caller _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'not721' // transfer to non ERC721Receiver implementer ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex && tokenId > 0; } function goat() public pure returns (string memory) { return '"Greatness is defined by how much you want to put into what you do." - LeBron James'; } function mintForAddress( uint256 quantity, address to ) public payable onlyValidAccess() { _mint(to, quantity); } function mint( uint256 quantity ) public payable { _mint(msg.sender, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity ) internal onlyValidAccess() { uint256 startTokenId = currentIndex; require(_owner == msg.sender || _mintIsOpen, 'Minting is currently closed'); // Don't allow anyone to mint if the mint is closed require(to != address(0), 'Cannot send to 0x0'); // mint to the 0x0 address require(quantity != 0, 'Quantity cannot be 0'); // quantity must be greater than 0 require(_owner == msg.sender || quantity <= _maxMintQuantity, 'Quantity exceeds mint max'); // quantity must be less than max quantity // The owner can mint for free, everyone else needs to pay the price require(_owner == msg.sender || msg.value >= _mintPrice * quantity, "Insufficient funds!"); require(currentIndex <= _maxSupply, 'No Hoops left!'); // sold out require(currentIndex + quantity <= _maxSupply, 'Not enough Hoops left to buy!'); // cannot mint more than maxIndex tokens unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, ''), 'Not ERC721Receiver' // transfer to non ERC721Receiver implementer ); updatedIndex++; } currentIndex = updatedIndex; } } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (msg.sender == prevOwnership.addr || getApproved(tokenId) == msg.sender || isApprovedForAll(prevOwnership.addr, msg.sender)); require(isApprovedOrOwner, 'Notapproved'); // transfer caller is not owner nor approved require(prevOwnership.addr == from, 'Invalid Owner'); // transfer from incorrect owner require(to != address(0), '0x'); // transfer to the zero address // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('not721'); // transfer to non ERC721Receiver implementer } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // ▓▓▓▓▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ░░████████████▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▓▓▓▓▓▓██ // ████▓▓▒▒▒▒▓▓████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████ // ▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▒▒▓▓ // ▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▓▓▓▓ // ▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒Welcome to the Hoops team▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██████████████▓▓████ // ▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▓▓████▓▓ // ▓▓▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░████▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░▓▓▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ▓▓██▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓ // ▓▓██▒▒▒▒▓▓▓▓██▓▓▓▓▓▓▓▓▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██ // ████████▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓██████▓▓██████▓▓▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████ // ▓▓▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒████████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ████▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒Please join us on discord at https://discord.gg/hoops▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ██▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ // ░░██▓▓▒▒▒▒▒▒▒▒████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░████▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▓▓▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░▓▓▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓ // ░░▓▓▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▓▓ // ░░████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▓▓ // ░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████▓▓▓▓ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ░░██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒ // ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ // ▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████ // ▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██░░ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓░░ // ░░▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▓▓▓▓██ // ▓▓██▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒████ // ██▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▓▓▓▓░░ // ██▓▓▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▓▓▓▓ // ▒▒██▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██░░ // ░░▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██░░░░ // ██████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████▓▓ // ▓▓▓▓██▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▓▓▓▓██ // ▓▓██▓▓██████████████████▓▓▓▓ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
% %%% .%..%...%..%...%..%. %%% %
bool _stickersEnabled = false;
14,482,721
[ 1, 9, 225, 738, 11438, 540, 263, 9, 838, 9, 2777, 9, 838, 9, 2777, 9, 838, 9, 18, 540, 738, 11438, 225, 738, 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 ]
[ 1, 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 ]
[ 1, 565, 1426, 389, 334, 1200, 414, 1526, 273, 629, 31, 4766, 6647, 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 ]
./full_match/1/0xaf50C9Cf53e1063AAaB84F089Da78b19f0a222a4/sources/contracts/utils/InitializableERC20Detailed.sol
* @dev Optional functions from the ERC20 standard. Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol @author Origin Protocol Inc/ Storage gap to skip storage from prior to OUSD reset
abstract contract InitializableERC20Detailed is IERC20 { uint256[100] private _____gap; string private _name; string private _symbol; uint8 private _decimals; function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg pragma solidity ^0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } }
3,150,206
[ 1, 6542, 4186, 628, 326, 4232, 39, 3462, 4529, 18, 4037, 329, 628, 1696, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 654, 39, 3462, 40, 6372, 18, 18281, 225, 18040, 4547, 15090, 19, 5235, 9300, 358, 2488, 2502, 628, 6432, 358, 531, 3378, 40, 2715, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 10188, 6934, 654, 39, 3462, 40, 6372, 353, 467, 654, 39, 3462, 288, 203, 565, 2254, 5034, 63, 6625, 65, 3238, 389, 7198, 14048, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 445, 389, 11160, 12, 203, 3639, 533, 3778, 508, 4117, 16, 203, 3639, 533, 3778, 3273, 4117, 16, 203, 3639, 2254, 28, 15105, 4117, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 288, 467, 654, 39, 3462, 289, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 3462, 19, 45, 654, 39, 3462, 18, 18281, 14432, 203, 565, 262, 2713, 288, 203, 3639, 389, 529, 273, 508, 4117, 31, 203, 3639, 389, 7175, 273, 3273, 4117, 31, 203, 3639, 389, 31734, 273, 15105, 4117, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.12; import './interface/ComptrollerInterface.sol'; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error MarketNotList(); error InsufficientLiquidity(); error PriceError(); error NotLiquidatePosition(); error AdminOnly(); error ProtocolPaused(); contract Comptroller is ComptrollerInterface { event NewAurumController(AurumControllerInterface oldAurumController, AurumControllerInterface newAurumController); event NewComptrollerCalculation(ComptrollerCalculation oldComptrollerCalculation, ComptrollerCalculation newComptrollerCalculation); event NewTreasuryGuardian(address oldTreasuryGuardian, address newTreasuryGuardian); event NewTreasuryAddress(address oldTreasuryAddress, address newTreasuryAddress); event NewTreasuryPercent(uint oldTreasuryPercent, uint newTreasuryPercent); event ARMGranted(address recipient, uint amount); event NewPendingAdmin (address oldPendingAdmin,address newPendingAdmin); event NewAdminConfirm (address oldAdmin, address newAdmin); event DistributedGOLDVault(uint amount); // Variables declaration // address public admin; address public pendingAdmin; ComptrollerStorage public compStorage; ComptrollerCalculation public compCalculate; AurumControllerInterface public aurumController; address public treasuryGuardian; //Guardian of the treasury address public treasuryAddress; //Wallet Address uint256 public treasuryPercent; //Fee in percent of accrued interest with decimal 18 , This value is used in liquidate function of each LendToken bool internal locked; // reentrancy Guardian constructor(ComptrollerStorage compStorage_) { admin = msg.sender; compStorage = compStorage_; //Bind storage to the comptroller contract. locked = false; // reentrancyGuard Variable } // // Get parameters function // function isComptroller() external pure returns(bool){ // double check the contract return true; } function isProtocolPaused() external view returns(bool) { return compStorage.protocolPaused(); } function getMintedGOLDs(address minter) external view returns(uint) { // The ledger of user's AURUM minted is stored in ComptrollerStorage contract. return compStorage.getMintedGOLDs(minter); } function getComptrollerOracleAddress() external view returns(address) { return address(compStorage.oracle()); } function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) { return compStorage.getAssetsIn(account); } function getGoldMintRate() external view returns (uint) { return compStorage.goldMintRate(); } function addToMarket(LendTokenInterface lendToken) external{ compStorage.addToMarket(lendToken, msg.sender); } function exitMarket(address lendTokenAddress) external{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); /* Get sender tokensHeld and borrowBalance from the lendToken */ (uint tokensHeld, uint borrowBalance, ) = lendToken.getAccountSnapshot(msg.sender); /* Fail if the sender has a borrow balance */ if (borrowBalance != 0) { revert(); } // if All of user's tokensHeld allowed to redeem, then it's allowed to UNCOLLATERALIZED. this.redeemAllowed(lendTokenAddress, msg.sender, tokensHeld); // Execute change of state variable in ComptrollerStorage. compStorage.exitMarket(lendTokenAddress, msg.sender); } /*** Policy Hooks ***/ // Check if the account be allowed to mint tokens // This check only // 1. Protocol not pause // 2. The lendToken is listed // Then update the reward SupplyIndex function mintAllowed(address lendToken, address minter) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getMintGuardianPaused(lendToken), "mint is paused"); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, minter); } // // Redeem allowed will check // 1. is the asset is list in market ? // 2. had the redeemer entered the market ? // 3. predict the value after redeem and check. if the loan is over (shortfall) then user can't redeem. // 4. if all pass then redeem is allowed. // function redeemAllowed(address lendToken, address redeemer, uint redeemTokens) external{ // bool protocolPaused = compStorage.protocolPaused(); // if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken)) { //Can't redeem the asset which not list in market. revert MarketNotList(); } /* If the redeemer is not 'in' the market (this token not in collateral calculation), then we can bypass the liquidity check */ if (!compStorage.checkMembership(redeemer, LendTokenInterface(lendToken)) ) { return ; } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(redeemer, lendToken, redeemTokens, 0); if (shortfall != 0) { revert InsufficientLiquidity(); } compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, redeemer); } // // Borrow allowed will check // 1. is the asset listed in market ? // 2. if borrower not yet listed in market.accountMembership --> add the borrower in // 3. Check the price of oracle (is it still in normal status ?) // 4.1 Check borrow cap (if borrowing amount more than cap it's not allowed) // 4.2 Predict the loan after borrow. if the loan is over (shortfall) then user can't borrow. // 5. if all pass, return no ERROR. // function borrowAllowed(address lendToken, address borrower, uint borrowAmount) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.getBorrowGuardianPaused(lendToken)); if (!compStorage.isMarketListed(lendToken)) { revert MarketNotList(); } if (!compStorage.checkMembership(borrower, LendTokenInterface(lendToken)) ) { // previously we check that 'lendToken' is one of the verify LendToken, so make sure that this function is called by the verified lendToken not ATTACKER wallet. require(msg.sender == lendToken, "sender must be lendToken"); // the borrow token automatically addToMarket. compStorage.addToMarket(LendTokenInterface(lendToken), borrower); } if (compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendToken)) == 0) { revert PriceError(); } uint borrowCap = compStorage.getBorrowCaps(lendToken); // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = LendTokenInterface(lendToken).totalBorrows(); uint nextTotalBorrows = totalBorrows + borrowAmount; require(nextTotalBorrows < borrowCap, "borrow cap reached"); // if total borrow + pending borrow reach borrow cap --> error } uint shortfall; (, shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, lendToken, 0, borrowAmount); if (shortfall != 0) { revert InsufficientLiquidity(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // repay is mostly allowed. except the market is closed. // function repayBorrowAllowed(address lendToken, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!compStorage.isMarketListed(lendToken) ) { revert MarketNotList(); } // Keep the flywheel moving uint borrowIndex = LendTokenInterface(lendToken).borrowIndex(); compStorage.updateARMBorrowIndex(lendToken, borrowIndex); compStorage.distributeBorrowerARM(lendToken, borrower, borrowIndex); } // // Liquidate allowed will check // 1. is market listed ? // 2. is the borrower currently shortfall ? (run predict function without borrowing or redeeming) // 3. calculate the max repayAmount by formula borrowBalance * closeFactorMantissa (%) // 4. check if repayAmount > maximumClose then revert. // 5. if all pass => allowed // function liquidateBorrowAllowed(address lendTokenBorrowed, address lendTokenCollateral, address borrower, uint repayAmount) external view{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } if (!(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController)) || !compStorage.isMarketListed(lendTokenCollateral) ) { revert MarketNotList(); } /* The borrower must have shortfall in order to be liquidatable */ (, uint shortfall) = compCalculate.getHypotheticalAccountLiquidity(borrower, address(0), 0, 0); if (shortfall == 0) { revert NotLiquidatePosition(); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance; if (address(lendTokenBorrowed) != address(aurumController)) { //aurumController is GOLD aurum minting control borrowBalance = LendTokenInterface(lendTokenBorrowed).borrowBalanceStored(borrower); } else { borrowBalance = compStorage.getMintedGOLDs(borrower); } uint maxClose = compStorage.closeFactorMantissa() * borrowBalance / 1e18; if (repayAmount > maxClose) { revert InsufficientLiquidity(); } } // // SeizeAllowed will check // 1. check the lendToken Borrow and Collateral both are listed in market (aurumController also can be lendTokenBorrowed address) // // 2. lendToken Borrow and Collateral are in the same market (Comptroller) // 3. if all pass => (allowed). // // lendTokenBorrowed is the called LendToken or aurumController. function seizeAllowed(address lendTokenCollateral, address lendTokenBorrowed, address liquidator, address borrower) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.seizeGuardianPaused()); // We've added aurumController as a borrowed token list check for seize if (!compStorage.isMarketListed(lendTokenCollateral) || !(compStorage.isMarketListed(lendTokenBorrowed) || address(lendTokenBorrowed) == address(aurumController))) { revert MarketNotList(); } // Check Borrow and Collateral in the same market (comptroller). if (LendTokenInterface(lendTokenCollateral).comptroller() != LendTokenInterface(lendTokenBorrowed).comptroller()) { revert(); } // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendTokenCollateral); compStorage.distributeSupplierARM(lendTokenCollateral, borrower); compStorage.distributeSupplierARM(lendTokenCollateral, liquidator); } // // TransferAllowed is simply automatic allowed when redeeming is allowed (redeeming then transfer) // So just check if this token is redeemable ? // function transferAllowed(address lendToken, address src, address dst, uint transferTokens) external{ bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } // Pausing is a very serious situation - we revert to sound the alarms require(!compStorage.transferGuardianPaused()); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens this.redeemAllowed(lendToken, src, transferTokens); // Keep the flywheel moving compStorage.updateARMSupplyIndex(lendToken); compStorage.distributeSupplierARM(lendToken, src); compStorage.distributeSupplierARM(lendToken, dst); } /*** Liquidity/Liquidation Calculations ***/ // Calculating function in ComptrollerCalculation contract function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateCalculateSeizeTokens(lendTokenBorrowed, lendTokenCollateral, actualRepayAmount); } function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { return compCalculate.liquidateGOLDCalculateSeizeTokens(lendTokenCollateral, actualRepayAmount); } // /*** Admin Functions ***/ // function _setPendingAdmin(address newPendingAdmin) external { if(msg.sender != admin) { revert AdminOnly();} address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin (oldPendingAdmin, newPendingAdmin); } function _confirmNewAdmin() external { if(msg.sender != admin) { revert AdminOnly();} address oldAdmin = admin; address newAdmin = pendingAdmin; require(newAdmin != address(0), "Set pending admin first"); admin = pendingAdmin; pendingAdmin = address(0); //Also set ComptrollerStorage's new admin to the same as comptroller. compStorage._setNewStorageAdmin(newAdmin); emit NewAdminConfirm (oldAdmin, newAdmin); } function _setAurumController(AurumControllerInterface aurumController_) external{ if(msg.sender != admin) { revert AdminOnly();} AurumControllerInterface oldRate = aurumController; aurumController = aurumController_; emit NewAurumController(oldRate, aurumController_); } function _setTreasuryData(address newTreasuryGuardian, address newTreasuryAddress, uint newTreasuryPercent) external{ if (!(msg.sender == admin || msg.sender == treasuryGuardian)) { revert AdminOnly(); } require(newTreasuryPercent < 1e18, "treasury percent cap overflow"); address oldTreasuryGuardian = treasuryGuardian; address oldTreasuryAddress = treasuryAddress; uint oldTreasuryPercent = treasuryPercent; treasuryGuardian = newTreasuryGuardian; treasuryAddress = newTreasuryAddress; treasuryPercent = newTreasuryPercent; emit NewTreasuryGuardian(oldTreasuryGuardian, newTreasuryGuardian); emit NewTreasuryAddress(oldTreasuryAddress, newTreasuryAddress); emit NewTreasuryPercent(oldTreasuryPercent, newTreasuryPercent); } function _setComptrollerCalculation (ComptrollerCalculation newCompCalculate) external { if(msg.sender != admin) { revert AdminOnly();} ComptrollerCalculation oldCompCalculate = compCalculate; compCalculate = newCompCalculate; emit NewComptrollerCalculation (oldCompCalculate, newCompCalculate); } // Claim ARM function function claimARMAllMarket(address holder) external { return claimARM(holder, compStorage.getAllMarkets()); } function claimARM(address holder, LendTokenInterface[] memory lendTokens) public { this.claimARM(holder, lendTokens, true, true); } function claimARM(address holder, LendTokenInterface[] memory lendTokens, bool borrowers, bool suppliers) external { require (locked == false,"No reentrance"); //Reentrancy guard locked = true; for (uint i = 0; i < lendTokens.length; i++) { LendTokenInterface lendToken = lendTokens[i]; require(compStorage.isMarketListed(address(lendToken))); uint armAccrued; if (borrowers) { // Update the borrow index of each lendToken in the storage of comptroller // Borrow index is the multiplier which gradually increase by the amount of interest (borrowRate) uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); compStorage.distributeBorrowerARM(address(lendToken), holder, borrowIndex); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); //reward the user then set user's armAccrued to 0; } if (suppliers) { compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.distributeSupplierARM(address(lendToken), holder); armAccrued = compStorage.getArmAccrued(holder); compStorage.grantARM(holder, armAccrued); } } locked = false; } /*** Aurum Distribution Admin ***/ function _setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external { if(msg.sender != admin) { revert AdminOnly();} uint borrowIndex = lendToken.borrowIndex(); compStorage.updateARMSupplyIndex(address(lendToken)); compStorage.updateARMBorrowIndex(address(lendToken), borrowIndex); uint currentAurumSpeed = compStorage.getAurumSpeeds(address(lendToken)); if (currentAurumSpeed == 0 && aurumSpeed != 0) { // Initialize compStorage.addARMdistributionMarket(lendToken); } if (currentAurumSpeed != aurumSpeed) { compStorage.setAurumSpeed(lendToken, aurumSpeed); } } //Set the amount of GOLD had minted, this should be called by aurumController contract function setMintedGOLDOf(address owner, uint amount) external { require(msg.sender == address(aurumController)); bool protocolPaused = compStorage.protocolPaused(); if(protocolPaused){ revert ProtocolPaused(); } bool mintGOLDGuardianPaused = compStorage.mintGOLDGuardianPaused(); require(!mintGOLDGuardianPaused, "Mint GOLD is paused"); compStorage.setMintedGOLD(owner,amount); } } contract ComptrollerCalculation { // no admin setting in this contract, ComptrollerStorage compStorage; constructor(ComptrollerStorage _compStorage) { compStorage = _compStorage; } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `lendTokenBalance` is the number of lendTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint lendTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; uint goldOraclePriceMantissa; uint tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return 1. account liquidity in excess of collateral requirements, * 2. account shortfall below collateral requirements) */ function getAccountLiquidity(address account) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(address(0)), 0, 0); return (liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ // // This function will simulate the user's account after interact with a specify LendToken when increasing loan (Borrowing and Redeeming) // How much liquidity left OR How much shortage will return. // 1. get each aset that the account participate in the market // 2. Sum up Collateral value (+), Borrow (-), Effect[BorrowMore, RedeemMore, Gold Minted] (-) // 3. Return liquidity if positive, Return shortage if negative. // function getHypotheticalAccountLiquidity(address account, address lendTokenModify, uint redeemTokens, uint borrowAmount) external view returns (uint, uint) { (uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(lendTokenModify), redeemTokens, borrowAmount); return (liquidity, shortfall); } function isShortage(address account) external view returns(bool){ // This function will be called by the front-end Liquidator query. the LendTokenInterface(msg.sender) is the dummy parameter, it's not use for calculation. (,uint shortfall) = getHypotheticalAccountLiquidityInternal(account, LendTokenInterface(msg.sender), 0, 0); if(shortfall > 0){ return true; } else { return false; } } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param lendTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral lendToken using stored data, * without calculating accumulated interest. * @return (hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, LendTokenInterface lendTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results vars.goldOraclePriceMantissa = compStorage.oracle().getGoldPrice(); if (vars.goldOraclePriceMantissa == 0) { revert ("Gold price error"); } // For each asset the account is in LendTokenInterface[] memory assets = compStorage.getAssetsIn(account); for (uint i = 0; i < assets.length; i++) { LendTokenInterface asset = assets[i]; // Read the balances and exchange rate from the lendToken // As noted above, if no one interact with the LendToken, the 'accrueInterest' function not called for long time. // May lead to outdated exchangeRate. (vars.lendTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); uint collateralFactorMantissa = compStorage.getMarketCollateralFactorMantissa(address(asset)); // Get the normalized price of the asset vars.oraclePriceMantissa = compStorage.oracle().getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { revert("Oracle error"); } // Pre-compute a conversion factor // Unit compensate = 1e18 :: (e18*e18 / e18) *e18 / e18 vars.tokensToDenom = (collateralFactorMantissa * vars.exchangeRateMantissa / 1e18) * vars.oraclePriceMantissa / 1e18; // sumCollateral += tokensToDenom * lendTokenBalance // Unit compensate = 1e18 :: (e18*e18 / e18) vars.sumCollateral += (vars.tokensToDenom * vars.lendTokenBalance / 1e18); // sumBorrowPlusEffects += oraclePrice * borrowBalance // Unit compensate = 1e18 :: (e18*e18 /e18) vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * vars.borrowBalance / 1e18); // Calculate effects of interacting with lendTokenModify if (asset == lendTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.tokensToDenom * redeemTokens / 1e18); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount // Unit compensate = 1e18 vars.sumBorrowPlusEffects += (vars.oraclePriceMantissa * borrowAmount / 1e18); } } //---------------------- This formula modified from VAI minted of venus contract to => GoldMinted * GoldOraclePrice------------------ // sumBorrowPlusEffects += GoldMinted * GoldOraclePrice vars.sumBorrowPlusEffects += (vars.goldOraclePriceMantissa * compStorage.getMintedGOLDs(account) / 1e18); // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { //Return remaining liquidity. return (vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { //Return shortfall amount. return (0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in lendToken.liquidateBorrowFresh) * @param lendTokenBorrowed The address of the borrowed lendToken * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of underlying token that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateCalculateSeizeTokens(address lendTokenBorrowed, address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenBorrowed)); uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation. Called by AurumController contract * @param lendTokenCollateral The address of the collateral lendToken * @param actualRepayAmount The amount of AURUM that liquidator had paid. * @return number of lendTokenCollateral tokens to be seized in a liquidation */ function liquidateGOLDCalculateSeizeTokens(address lendTokenCollateral, uint actualRepayAmount) external view returns (uint) { /* Read oracle prices for borrowed and collateral markets */ //The different to the previous function is only Borrow price oracle is GOLD price uint priceBorrowedMantissa = compStorage.oracle().getGoldPrice(); // get the current gold price feeding from oracle uint priceCollateralMantissa = compStorage.oracle().getUnderlyingPrice(LendTokenInterface(lendTokenCollateral)); if (priceCollateralMantissa == 0 || priceBorrowedMantissa == 0) { revert ("Oracle price error"); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = LendTokenInterface(lendTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; // Numerator is 1e54 // *1e18 for calculating ratio into 1e18 uint numerator = compStorage.liquidationIncentiveMantissa() * priceBorrowedMantissa * 1e18; // Denominator is 1e36 uint denominator = priceCollateralMantissa * exchangeRateMantissa; // Ratio is 1e18 uint ratioMantissa = numerator / denominator; seizeTokens = ratioMantissa * actualRepayAmount / 1e18; return seizeTokens; } struct ARMAccrued { uint supplierIndex; uint borrowerIndex; uint supplyStateIndex; uint borrowStateIndex; uint supplierTokens; uint borrowerAmount; uint aurumSpeed; } // // Front-end function // core function is getUpdateARMAccrued // input of timestamp in Javascript should be divided by 1000 // function getUpdateARMSupplyIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint supplyStateIndex, uint supplyStateTimestamp) = compStorage.armSupplyState(lendToken); uint supplySpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - supplyStateTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } return supplyStateIndex + addingValue; } else { return supplyStateIndex; } } function getUpdateARMBorrowIndex(address lendToken, uint currentTime) internal view returns(uint) { (uint borrowStateIndex, uint borrowStateTimestamp) = compStorage.armBorrowState(lendToken); uint borrowSpeed = compStorage.aurumSpeeds(lendToken); uint deltaTime = currentTime - borrowStateTimestamp; uint marketBorrowIndex = LendTokenInterface(lendToken).borrowIndex(); if (deltaTime > 0 && borrowSpeed > 0) { uint borrowTokens = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; // addingValue is e36 uint addingValue; if (borrowTokens > 0){ addingValue = armAcc * 1e36 / borrowTokens; // calculate index and stored in Double } else { addingValue = 0; } return borrowStateIndex + addingValue; } else { return borrowStateIndex; } } // This function called by front-end dApp to get real-time reward function getUpdateARMAccrued(address user, uint currentTime) external view returns(uint) { LendTokenInterface[] memory lendToken = compStorage.getAllMarkets(); ARMAccrued memory vars; uint priorARMAccrued = compStorage.getArmAccrued(user); uint i; uint deltaIndex; uint marketBorrowIndex; for(i=0;i<lendToken.length; i++){ vars.supplierIndex = compStorage.aurumSupplierIndex(address(lendToken[i]) , user); vars.borrowerIndex = compStorage.aurumBorrowerIndex(address(lendToken[i]) , user); vars.supplyStateIndex = getUpdateARMSupplyIndex(address(lendToken[i]), currentTime); vars.borrowStateIndex = getUpdateARMBorrowIndex(address(lendToken[i]), currentTime); marketBorrowIndex = lendToken[i].borrowIndex(); vars.aurumSpeed = compStorage.aurumSpeeds(address(lendToken[i])); //Supply Accrued if (vars.supplierIndex == 0 && vars.supplyStateIndex > 0) { vars.supplierIndex = 1e36; } deltaIndex = vars.supplyStateIndex - vars.supplierIndex; vars.supplierTokens = lendToken[i].balanceOf(user); priorARMAccrued += vars.supplierTokens * deltaIndex / 1e36; //Borrow Accrued if (vars.borrowerIndex > 0) { deltaIndex = vars.borrowStateIndex - vars.borrowerIndex; vars.borrowerAmount = lendToken[i].borrowBalanceStored(user) * 1e18 / marketBorrowIndex; priorARMAccrued += vars.borrowerAmount * deltaIndex / 1e36; } } return priorARMAccrued; } } contract ComptrollerStorage { event MarketListed(LendTokenInterface lendToken); event MarketEntered(LendTokenInterface lendToken, address account); event MarketExited(LendTokenInterface lendToken, address account); event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); event NewCollateralFactor(LendTokenInterface lendToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); event AurumSpeedUpdated(LendTokenInterface indexed lendToken, uint newSpeed); event DistributedSupplierARM(LendTokenInterface indexed lendToken, address indexed supplier, uint aurumDelta, uint aurumSupplyIndex); event DistributedBorrowerARM(LendTokenInterface indexed lendToken, address indexed borrower, uint aurumDelta, uint aurumBorrowIndex); event NewGOLDMintRate(uint oldGOLDMintRate, uint newGOLDMintRate); event ActionProtocolPaused(bool state); event ActionTransferPaused(bool state); event ActionSeizePaused(bool state); event ActionMintPaused(address lendToken, bool state); event ActionBorrowPaused(address lendToken, bool state); event NewGuardianAddress(address oldGuardian, address newGuardian); event NewBorrowCap(LendTokenInterface indexed lendToken, uint newBorrowCap); event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); event MintGOLDPause(bool state); address public armAddress; address public comptrollerAddress; address public admin; address public guardian; //Guardian address, can only stop protocol PriceOracle public oracle; //stored contract of current PriceOracle (can be changed by _setPriceOracle function) function getARMAddress() external view returns(address) {return armAddress;} // // Liquidation variables // //Close factor is the % (in 1e18 value) of borrowing asset can be liquidate //e.g. if set 50% --> borrow 1000 USD, position can be liquidate maximum of 500 USD uint public closeFactorMantissa; //calculate the maximum repayAmount when liquidating a borrow --> can be set by _setCloseFactor(uint) uint public liquidationIncentiveMantissa; //multiplier that liquidator will receive after successful liquidate ; venus comptroller set up = 1100000000000000000 (1.1e18) // // Pause variables // /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing can only be paused globally, not by market. */ bool public protocolPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; function getMintGuardianPaused(address lendTokenAddress) external view returns(bool){ return mintGuardianPaused[lendTokenAddress];} mapping(address => bool) public borrowGuardianPaused; function getBorrowGuardianPaused(address lendTokenAddress) external view returns(bool){ return borrowGuardianPaused[lendTokenAddress];} bool public mintGOLDGuardianPaused; mapping(address => uint) public armAccrued; //ARM accrued but not yet transferred to each user function getArmAccrued(address user) external view returns (uint) {return armAccrued[user];} // // Aurum Gold controller 'AURUM token' // mapping(address => uint) public mintedGOLDs; //minted Aurum GOLD amount to each user function getMintedGOLDs(address user) external view returns(uint) {return mintedGOLDs[user];} uint16 public goldMintRate; //GOLD Mint Rate (percentage) value with two decimals 0-10000, 100 = 1%, 1000 = 10%, // // ARM distribution variables // mapping(address => uint) public aurumSpeeds; //The portion of aurumRate that each market currently receives function getAurumSpeeds(address lendToken) external view returns(uint) { return aurumSpeeds[lendToken];} // // Borrow cap // mapping(address => uint) public borrowCaps; //borrowAllowed for each lendToken address. Defaults to zero which corresponds to unlimited borrowing. function getBorrowCaps(address lendTokenAddress) external view returns (uint) { return borrowCaps[lendTokenAddress];} // // Market variables // mapping(address => LendTokenInterface[]) public accountAssets; //stored each account's assets. function getAssetsIn(address account) external view returns (LendTokenInterface[] memory) {return accountAssets[account];} struct Market { bool isListed; //Listed = true, Not listed = false /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; mapping(address => bool) accountMembership; //Each market mapping of "accounts in this asset" similar to 'accountAssets' variable but the market side. } /** * @notice Official mapping of lendTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; //Can be set by _supportMarket admin function. function checkMembership(address account, LendTokenInterface lendToken) external view returns (bool) {return markets[address(lendToken)].accountMembership[account];} function isMarketListed(address lendTokenAddress) external view returns (bool) {return markets[lendTokenAddress].isListed;} function getMarketCollateralFactorMantissa(address lendTokenAddress) external view returns (uint) {return markets[lendTokenAddress].collateralFactorMantissa;} struct TheMarketState { /// @notice The market's last updated aurumBorrowIndex or aurumSupplyIndex // index variable is in Double (1e36) stored the last update index uint index; /// @notice The block number the index was last updated at uint lastTimestamp; } LendTokenInterface[] public allMarkets; //A list of all markets function getAllMarkets() external view returns(LendTokenInterface[] memory) {return allMarkets;} mapping(address => TheMarketState) public armSupplyState; //market supply state for each market mapping(address => TheMarketState) public armBorrowState; //market borrow state for each market //Individual index variables will update once individual check allowed function (will lastly call distributeSupplier / distributeBorrower function) to the current market's index. mapping(address => mapping(address => uint)) public aurumSupplierIndex; //supply index of each market for each supplier as of the last time they accrued ARM mapping(address => mapping(address => uint)) public aurumBorrowerIndex; //borrow index of each market for each borrower as of the last time they accrued ARM /// @notice The portion of ARM that each contributor receives per block mapping(address => uint) public aurumContributorSpeeds; /// @notice Last block at which a contributor's ARM rewards have been allocated mapping(address => uint) public lastContributorBlock; /// @notice The initial Aurum index for a market uint224 constant armInitialIndex = 1e36; // // CloseFactorMantissa guide // uint public constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must be strictly greater than this value ** MIN 5% uint public constant closeFactorMaxMantissa = 0.9e18; // 0.9 // closeFactorMantissa must not exceed this value ** MAX 90% uint public constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value constructor(address _armAddress) { admin = msg.sender; armAddress = _armAddress; closeFactorMantissa = 0.5e18; liquidationIncentiveMantissa = 1.1e18; } // // Comptroller parameter change function // Require comptroller is msg.sender // modifier onlyComptroller { require (msg.sender == comptrollerAddress, "Only comptroller"); _; } function _setNewStorageAdmin(address newAdmin) external onlyComptroller { admin = newAdmin; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param lendToken The market to enter * @param borrower The address of the account to modify */ function addToMarket(LendTokenInterface lendToken, address borrower) external onlyComptroller { Market storage marketToJoin = markets[address(lendToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join revert ("MARKET_NOT_LISTED"); } if (marketToJoin.accountMembership[borrower]) { // already joined return ; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(lendToken); emit MarketEntered(lendToken, borrower); } // To exitMarket.. Checking condition // --user must not borrowing this asset, // --user is allowed to redeem all the tokens (no excess loan when hypotheticalLiquidityCheck) // Action // 1.trigger boolean of user address of market's accountMembership to false // 2.delete userAssetList to this market. // function exitMarket(address lendTokenAddress, address user) external onlyComptroller{ LendTokenInterface lendToken = LendTokenInterface(lendTokenAddress); Market storage marketToExit = markets[address(lendToken)]; /* Return out if the sender is not ‘in’ the market */ if (!marketToExit.accountMembership[user]) { return ; //the state variable had changed in redeemAllowed function (updateARMSupplyIndex, distributeSupplierARM) } /* Set lendToken account membership to false */ delete marketToExit.accountMembership[user]; /* Delete lendToken from the account’s list of assets */ // In order to delete lendToken, copy last item in list to location of item to be removed, reduce length by 1 LendTokenInterface[] storage userAssetList = accountAssets[user]; uint len = userAssetList.length; uint i; for (i=0 ; i < len ; i++) { if (userAssetList[i] == lendToken) { // found the deleting array userAssetList[i] = userAssetList[len - 1]; // move the last parameter in array to the deleting array userAssetList.pop(); //this function remove the last parameter and also reduce array length by 1 break; //break before i++ so if there is the asset list, 'i' must always lesser than 'len' } } // We *must* have found the asset in the list or our redundant data structure is broken assert(i < len); emit MarketExited(lendToken, user); } function setAurumSpeed(LendTokenInterface lendToken, uint aurumSpeed) external onlyComptroller { // This function called by comptroller's _setAurumSpeed //Update the aurumSpeeds state variable. aurumSpeeds[address(lendToken)] = aurumSpeed; emit AurumSpeedUpdated(lendToken, aurumSpeed); } // This function is called by _setAurumSpeed admin function when FIRST TIME starting distribute ARM reward (from aurumSpeed 0) // it will check the MarketState of this lendToken and set to InitialIndex function addARMdistributionMarket(LendTokenInterface lendToken) external onlyComptroller { // Add the ARM market Market storage market = markets[address(lendToken)]; require(market.isListed == true, "aurum market is not listed"); // // These Lines of code is modified from Venus // If someone had mint lendToken or Allowed function is called, the timestamp would be change and not equal to zero // /* if (armSupplyState[address(lendToken)].index == 0 && armSupplyState[address(lendToken)].lastTimestamp == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0 && armBorrowState[address(lendToken)].lastTimestamp == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } */ // // We remove the timeStamp == 0 , once distribution is initiated the index will not back to zero again. // This prevent over-reward of ARM if someone is pre-supply before the reward is initiating distribution. // if (armSupplyState[address(lendToken)].index == 0) { armSupplyState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } if (armBorrowState[address(lendToken)].index == 0) { armBorrowState[address(lendToken)] = TheMarketState({ index: armInitialIndex, lastTimestamp: block.timestamp }); } } //Update the ARM distribute to Supplier //This function update the armSupplyState function updateARMSupplyIndex(address lendToken) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplySpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - supplyState.lastTimestamp; if (deltaTime > 0 && supplySpeed > 0) { uint supplyTokens = LendTokenInterface(lendToken).totalSupply(); uint armAcc = deltaTime * supplySpeed; // addingValue is e36 uint addingValue; if (supplyTokens > 0){ addingValue = armAcc * 1e36 / supplyTokens; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = supplyState.index + addingValue; armSupplyState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { supplyState.lastTimestamp = currentTime; } } //Update the ARM distribute to Borrower //same as above function but interact with Borrower variables function updateARMBorrowIndex(address lendToken, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowSpeed = aurumSpeeds[lendToken]; uint currentTime = block.timestamp; uint deltaTime = currentTime - borrowState.lastTimestamp; if (deltaTime > 0 && borrowSpeed > 0) { //borrowAmount is 1e18 :: e18 * 1e18 / e18 uint borrowAmount = LendTokenInterface(lendToken).totalBorrows() * 1e18 / marketBorrowIndex; uint armAcc = deltaTime * borrowSpeed; uint addingValue; if (borrowAmount > 0){ addingValue = armAcc * 1e36 / borrowAmount; // calculate index and stored in Double } else { addingValue = 0; } uint newindex = borrowState.index + addingValue; armBorrowState[lendToken] = TheMarketState({ index: newindex, // setting new updated index lastTimestamp: currentTime //and also timestamp }); } else if (deltaTime > 0) { borrowState.lastTimestamp = currentTime; } } //Distribute function will update armAccrued depends on the State.index which update by updateARM function //armAccrued will later claim by claimARM function function distributeSupplierARM(address lendToken, address supplier) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; uint supplyIndex = supplyState.index; // stored in 1e36 uint supplierIndex = aurumSupplierIndex[lendToken][supplier]; // stored in 1e36 aurumSupplierIndex[lendToken][supplier] = supplyIndex; // update the user's index to the current state if (supplierIndex == 0 && supplyIndex > 0) { //This happen when first time using Allowed function after initialized reward distribution (Mint/Redeem/Seize) //or receiving a lendToken but currently don't have this token (transferAllowed function) supplierIndex = armInitialIndex; // 1e36 } //Calculate the new accrued arm since last update uint deltaIndex = supplyIndex - supplierIndex; uint supplierTokens = LendTokenInterface(lendToken).balanceOf(supplier); //e18 //If first time Mint/receive transfer LendToken, the balanceOf should be 0 uint supplierDelta = supplierTokens * deltaIndex / 1e36; //e18 :: e18*e36/ 1e36 uint supplierAccrued = armAccrued[supplier] + supplierDelta; armAccrued[supplier] = supplierAccrued; emit DistributedSupplierARM(LendTokenInterface(lendToken), supplier, supplierDelta, supplyIndex); } function distributeBorrowerARM(address lendToken, address borrower, uint marketBorrowIndex) external onlyComptroller { TheMarketState storage borrowState = armBorrowState[lendToken]; uint borrowIndex = borrowState.index; // stored in 1e36 uint borrowerIndex = aurumBorrowerIndex[lendToken][borrower]; // stored in 1e36 aurumBorrowerIndex[lendToken][borrower] = borrowIndex; // update the user's index to the current state if (borrowerIndex > 0) { uint deltaIndex = borrowIndex - borrowerIndex; // e36 // Let explain in diagram // [p] = principal // [i] = interest // [/i] = interest not yet record in accountBorrows[user] // [p][p][p][p][i] principal with interest (accountBorrows[user] stored 1. principal and 2.interestIndex multiplier) // [p][p][p][p] principal / interestIndex // [p][p][p][p][/i][/i] principal / interestIndex * marketBorrowIndex (this is what borrowBalanceStored function returns); // We need only principal amount to be calculated. uint borrowerAmount = LendTokenInterface(lendToken).borrowBalanceStored(borrower) * 1e18 / marketBorrowIndex; // e18 //This result uint borrowerDelta = borrowerAmount * deltaIndex / 1e36; // e18 :: e18 * e36 / 1e36 uint borrowerAccrued = armAccrued[borrower] + borrowerDelta; armAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerARM(LendTokenInterface(lendToken), borrower, borrowerDelta, borrowIndex); } } //called by claimARM function //This function execute change of state variable 'armAccrued' and transfer ARM token to user. //returns the pending reward after claim. by the way it's not necessory. function grantARM(address user, uint amount) external onlyComptroller returns (uint) { IERC20 arm = IERC20(armAddress); uint armRemaining = arm.balanceOf(address(this)); // when the ARM reward pool is nearly empty, admin should manually turn aurum speed to 0 //Treasury reserves will be used when there is human error in reward process. if (amount > 0 && amount <= armRemaining) { armAccrued[user] = 0; arm.transfer(user, amount); return 0; } return amount; } function setMintedGOLD(address owner, uint amount) external onlyComptroller{ mintedGOLDs[owner] = amount; } // // Admin function // function _setComptrollerAddress (address newComptroller) external { require(msg.sender == admin, "Only admin"); comptrollerAddress = newComptroller; } // Maximum % of borrowing position can be liquidated (stored in 1e18) function _setCloseFactor(uint newCloseFactorMantissa) external { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, newCloseFactorMantissa); } function _setCollateralFactor(LendTokenInterface lendToken, uint newCollateralFactorMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // Verify market is listed Market storage market = markets[address(lendToken)]; if (!market.isListed) { revert ("Market not listed"); } // Check collateral factor <= 0.9 uint highLimit = collateralFactorMaxMantissa; require (highLimit > newCollateralFactorMantissa); // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(lendToken) == 0) { revert ("Fail price oracle"); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(lendToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); } // LiquidativeIncentive is > 1.00 // if set 1.1e18 means liquidator get 10% of liquidated position function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); require(newLiquidationIncentiveMantissa >= 1e18,"value must greater than 1e18"); // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); } // Add the market to the markets mapping and set it as listed function _supportMarket(LendTokenInterface lendToken) external{ require(msg.sender == admin, "Only admin"); if (markets[address(lendToken)].isListed) { revert ("Already list"); } require (lendToken.isLendToken(),"Not lendToken"); // Sanity check to make sure its really a LendTokenInterface markets[address(lendToken)].isListed = true; markets[address(lendToken)].collateralFactorMantissa = 0; for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != lendToken, "Already added"); } allMarkets.push(lendToken); emit MarketListed(lendToken); } //Set borrowCaps function _setMarketBorrowCaps(LendTokenInterface[] calldata lendTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin, "Only admin"); uint numMarkets = lendTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(lendTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(lendTokens[i], newBorrowCaps[i]); } } /** * Set whole protocol pause/unpause state */ function _setGuardianAddress(address newGuardian) external { require(msg.sender == admin, "No Auth"); address oldGuardian = guardian; guardian = newGuardian; emit NewGuardianAddress(oldGuardian, newGuardian); } //Guardians can pause protocol but can't unpause function _setProtocolPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); protocolPaused = state; emit ActionProtocolPaused(state); } function _setTransferPaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); transferGuardianPaused = state; emit ActionTransferPaused(state); } function _setSeizePaused(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); seizeGuardianPaused = state; emit ActionSeizePaused(state); } function _setMintPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGuardianPaused[lendToken] = state; emit ActionMintPaused(lendToken, state); } function _setBorrowPaused(address lendToken, bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); borrowGuardianPaused[lendToken] = state; emit ActionBorrowPaused(lendToken, state); } function _setMintGoldPause(bool state) external { require(msg.sender == admin || (msg.sender == guardian && state == true), "No Auth"); mintGOLDGuardianPaused = state; emit MintGOLDPause(state); } function _setGOLDMintRate(uint16 newGOLDMintRate) external{ require(msg.sender == admin, "Only admin"); // Input: 0-10000, percentage with 2 decimals // 1 = 0.01% // 100 = 1% // 10000 = 100% // Check caller is admin require (newGOLDMintRate > 0 && newGOLDMintRate <= 10000,"Mintable GOLD rate must value 0-10000"); uint oldGOLDMintRate = goldMintRate; goldMintRate = newGOLDMintRate; emit NewGOLDMintRate(oldGOLDMintRate, newGOLDMintRate); } /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle */ function _setPriceOracle(PriceOracle newOracle) external{ // Check caller is admin require(msg.sender == admin, "Only admin"); // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); } }
Distribute function will update armAccrued depends on the State.index which update by updateARM functionarmAccrued will later claim by claimARM function
function distributeSupplierARM(address lendToken, address supplier) external onlyComptroller { TheMarketState storage supplyState = armSupplyState[lendToken]; if (supplierIndex == 0 && supplyIndex > 0) { } uint supplierAccrued = armAccrued[supplier] + supplierDelta; armAccrued[supplier] = supplierAccrued; emit DistributedSupplierARM(LendTokenInterface(lendToken), supplier, supplierDelta, supplyIndex); uint deltaIndex = supplyIndex - supplierIndex; }
15,849,594
[ 1, 1669, 887, 445, 903, 1089, 23563, 8973, 86, 5957, 10935, 603, 326, 3287, 18, 1615, 1492, 1089, 635, 225, 1089, 26120, 225, 445, 4610, 8973, 86, 5957, 903, 5137, 7516, 635, 7516, 26120, 445, 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, 565, 445, 25722, 13254, 26120, 12, 2867, 328, 409, 1345, 16, 1758, 17402, 13, 3903, 1338, 799, 337, 1539, 288, 203, 3639, 1021, 3882, 278, 1119, 2502, 14467, 1119, 273, 23563, 3088, 1283, 1119, 63, 80, 409, 1345, 15533, 203, 203, 3639, 309, 261, 2859, 5742, 1016, 422, 374, 597, 14467, 1016, 405, 374, 13, 288, 377, 203, 3639, 289, 203, 203, 3639, 2254, 17402, 8973, 86, 5957, 273, 23563, 8973, 86, 5957, 63, 2859, 5742, 65, 397, 17402, 9242, 31, 203, 3639, 23563, 8973, 86, 5957, 63, 2859, 5742, 65, 273, 17402, 8973, 86, 5957, 31, 203, 3639, 3626, 27877, 13254, 26120, 12, 48, 409, 1345, 1358, 12, 80, 409, 1345, 3631, 17402, 16, 17402, 9242, 16, 14467, 1016, 1769, 203, 3639, 2254, 3622, 1016, 273, 14467, 1016, 300, 17402, 1016, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.8.4; import {IFactory} from "./interfaces/IFactory.sol"; import {ISwap, Types} from "./airswap/interfaces/ISwap.sol"; import {IAddressBook} from "./gamma/interfaces/IAddressBook.sol"; import {Actions, GammaTypes, IController} from "./gamma/interfaces/IController.sol"; import {OtokenInterface} from "./gamma/interfaces/OtokenInterface.sol"; import {ERC20Upgradeable} from "../oz/token/ERC20/ERC20Upgradeable.sol"; import {ERC20, IERC20} from "../oz/token/ERC20/ERC20.sol"; import {SafeERC20} from "../oz/token/ERC20/utils/SafeERC20.sol"; import {PausableUpgradeable} from "../oz/security/PausableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "../oz/security/ReentrancyGuardUpgradeable.sol"; contract VaultToken is ERC20Upgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; error Unauthorized(); error Unauthorized_COUNTERPARTY_DID_NOT_SIGN(); error Invalid(); error NotEnoughFunds(); error NotEnoughFunds_ReserveViolation(); error MaximumFundsReached(); error RatioAlreadyDefined(); error WithdrawalWindowNotActive(); error WithdrawalWindowActive(); error oTokenNotCleared(); error SettlementNotReady(); error ClosedPermanently(); /// @notice Time in which the withdrawal window expires uint256 public withdrawalWindowExpires; /// @notice Length of time where the withdrawal window is active uint256 public withdrawalWindowLength; /// @notice Amount of collateral for the address already used for collateral uint256 public collateralAmount; /// @notice Current active vault uint256 private currentVaultId; /// @notice Maximum funds uint256 public maximumAssets; /// @notice Obligated fees to the manager uint256 public obligatedFees; /// @notice Deposit fee uint16 public depositFee; /// @notice Take profit fee uint16 public withdrawalFee; /// @notice Performance fee (taken when options are sold) uint16 public performanceFee; /// @notice Withdrawal reserve percentage uint16 public withdrawalReserve; /// @notice Current reserves uint256 public currentReserves; /// @notice Address of the current oToken address public oToken; /// @notice Address of the AddressBook IAddressBook private addressBook; /// @notice Address of the underlying asset to trade address public asset; /// @notice Address of the manager (admin) address public manager; /// @notice Address of the factory IFactory public factory; /// @notice Determines if the vault is closed permanently bool public closedPermanently; event Deposit(uint256 assetDeposited, uint256 vaultTokensMinted); event Withdrawal(uint256 assetWithdrew, uint256 vaultTokensBurned); event WithdrawalWindowActivated(uint256 closesAfter); event OptionsMinted(uint256 collateralDeposited, address indexed newOtoken, uint256 vaultId); event OptionsBurned(uint256 oTokensBurned); event OptionsSold(uint256 amountSold, uint256 premiumReceived); event ReservesEstablished(uint256 allocatedReserves); event MaximumAssetsModified(uint256 newAUM); event DepositFeeModified(uint16 newFee); event WithdrawalFeeModified(uint16 newFee); event PerformanceFeeModified(uint16 newFee); event WithdrawalReserveModified(uint16 newReserve); modifier onlyManager { _onlyManager(); _; } modifier withdrawalWindowCheck(bool _revertIfClosed) { _withdrawalWindowCheck(_revertIfClosed); _; } function initialize( string memory _name, string memory _symbol, address _asset, address _manager, address _addressBook, address _factory, uint256 _withdrawalWindowLength, uint256 _maximumAssets ) external initializer { __ERC20_init_unchained(_name, _symbol); asset = _asset; manager = _manager; addressBook = IAddressBook(_addressBook); factory = IFactory(_factory); withdrawalWindowLength = _withdrawalWindowLength; maximumAssets = _maximumAssets; } /// @notice For emergency use /// @dev Stops all activities on the vault (or reactivates them) /// @param _pause true to pause the vault, false to unpause the vault function emergency(bool _pause) external onlyManager { if(_pause) super._pause(); else super._unpause(); } /// @notice Changes the maximum allowed deposits under management /// @dev Changes the maximumAssets to the new amount /// @param _newValue new maximumAssets value function adjustTheMaximumAssets(uint256 _newValue) external onlyManager nonReentrant() whenNotPaused() { if(_newValue < collateralAmount + IERC20(asset).balanceOf(address(this))) revert Invalid(); maximumAssets = _newValue; emit MaximumAssetsModified(_newValue); } /// @notice Changes the deposit fee /// @dev Changes the depositFee with two decimals of precision up to 50.00% (5000) /// @param _newValue new depositFee with two decimals of precision function adjustDepositFee(uint16 _newValue) external onlyManager nonReentrant() whenNotPaused() { if(_newValue > 5000) revert Invalid(); depositFee = _newValue; emit DepositFeeModified(_newValue); } /// @notice Changes the withdrawal fee /// @dev Changes the withdrawalFee with two decimals of precision up to 50.00% (5000) /// @param _newValue new withdrawalFee with two decimals of precision function adjustWithdrawalFee(uint16 _newValue) external onlyManager nonReentrant() whenNotPaused() { if(_newValue > 5000) revert Invalid(); withdrawalFee = _newValue; emit WithdrawalFeeModified(_newValue); } /// @notice Changes the performance fee /// @dev Changes the performanceFee with two decimals of precision up to 50.00% (5000) /// @param _newValue new performanceFee with two decimals of precision function adjustPerformanceFee(uint16 _newValue) external onlyManager nonReentrant() whenNotPaused() { if(_newValue > 5000) revert Invalid(); performanceFee = _newValue; emit PerformanceFeeModified(_newValue); } /// @notice Changes the withdrawal reserve percentage /// @dev Changes the withdrawalReserve with two decimals of precision up to 50.00% (5000) /// @param _newValue new withdrawalReserve with two decimals of precision function adjustWithdrawalReserve(uint16 _newValue) external onlyManager nonReentrant() whenNotPaused() { if(_newValue > 5000) revert Invalid(); withdrawalReserve = _newValue; emit WithdrawalReserveModified(_newValue); } /// @notice Changes the withdrawal window length /// @dev Changes the withdrawalWindowLength /// @param _newValue new withdrawalWindowLength period function adjustWithdrawalWindowLength(uint256 _newValue) external onlyManager nonReentrant() whenNotPaused() { withdrawalWindowLength = _newValue; } /// @notice Allows the manager to collect fees /// @dev Transfers all of the obligatedFees to the manager and sets it to zero function sweepFees() external onlyManager nonReentrant() whenNotPaused() { IERC20(asset).safeTransfer(msg.sender, obligatedFees); obligatedFees = 0; } /// @notice Deposit assets and receive vault tokens to represent a share /// @dev Deposits an amount of assets specified then mints vault tokens to the msg.sender /// @param _amount amount to deposit of ASSET function deposit(uint256 _amount) external nonReentrant() whenNotPaused() { if(closedPermanently) revert ClosedPermanently(); if(_amount == 0) revert Invalid(); if(collateralAmount + IERC20(asset).balanceOf(address(this)) + _amount - obligatedFees > maximumAssets) revert MaximumFundsReached(); uint256 vaultMint; uint256 protocolFees; uint256 vaultFees; // Calculate protocol-level fees if(factory.depositFee() != 0) { protocolFees = _percentMultiply(_amount, factory.depositFee()); } // Calculate vault-level fees if(depositFee != 0) { vaultFees = _percentMultiply(_amount, depositFee); } // Check if the total supply is zero if(totalSupply() == 0) { vaultMint = _normalize(_amount - protocolFees - vaultFees, ERC20(asset).decimals(), decimals()); withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; } else { vaultMint = totalSupply() * (_amount - protocolFees - vaultFees) / (IERC20(asset).balanceOf(address(this)) + collateralAmount - obligatedFees); } obligatedFees += vaultFees; if(vaultMint == 0) // Safety check for rounding errors revert Invalid(); IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount); if(protocolFees > 0) IERC20(asset).safeTransfer(factory.admin(), protocolFees); _mint(msg.sender, vaultMint); emit Deposit(_amount, vaultMint); } /// @notice Redeem vault tokens for assets /// @dev Burns vault tokens in redemption for the assets to msg.sender /// @param _amount amount of VAULT TOKENS to burn function withdraw(uint256 _amount) external nonReentrant() whenNotPaused() { if(_amount == 0) revert Invalid(); uint256 assetAmount = _amount * (IERC20(asset).balanceOf(address(this)) + collateralAmount - obligatedFees) / totalSupply(); uint256 protocolFee; uint256 vaultFee; if(factory.withdrawalFee() > 0) { protocolFee = _percentMultiply(_amount, factory.withdrawalFee()); IERC20(asset).safeTransfer(factory.admin(), protocolFee); } if(withdrawalFee > 0) { vaultFee = _percentMultiply(_amount, withdrawalFee); obligatedFees += vaultFee; } assetAmount -= (protocolFee + vaultFee); // Safety check if(assetAmount == 0) revert Invalid(); // (Reserve) safety check if(assetAmount > currentReserves && _withdrawalWindowCheck(false) && oToken != address(0)) revert NotEnoughFunds_ReserveViolation(); if(_withdrawalWindowCheck(false) && oToken != address(0)) currentReserves -= assetAmount; IERC20(asset).safeTransfer(msg.sender, assetAmount); // Vault Token Amount to Burn * Balance of Vault for Asset / Total Vault Token Supply _burn(address(msg.sender), _amount); emit Withdrawal(assetAmount, _amount); } /// @notice Allows anyone to call it in the event the withdrawal window is closed, but no action has occurred within 1 day /// @dev Reopens the withdrawal window for a minimum of one day, whichever is greater function reactivateWithdrawalWindow() external nonReentrant() whenNotPaused() { if(block.timestamp < withdrawalWindowExpires + 1 days) revert Invalid(); if(withdrawalWindowLength > 1 days) withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; else withdrawalWindowExpires = block.timestamp + 1 days; emit WithdrawalWindowActivated(withdrawalWindowExpires); } /// @notice Write calls for an _amount of asset for the specified oToken /// @dev Allows the manager to write calls for an x /// @param _amount amount of the asset to deposit as collateral /// @param _oToken address of the oToken function writeOptions(uint256 _amount, address _oToken) external onlyManager nonReentrant() whenNotPaused() { _writeOptions(_amount, _oToken); } /// @notice Write calls for a _percentage of the current balance of the vault /// @dev Uses percentage of the vault instead of a specific number (helpful for multi-sigs) /// @param _percentage A uint16 representing up to 10000 (100.00%) with two decimals of precision for the amount of asset tokens to write /// @param _oToken address of the oToken function writeOptions(uint16 _percentage, address _oToken) external onlyManager nonReentrant() whenNotPaused() { if(_percentage > 10000) revert Invalid(); if(_percentage > _percentage - withdrawalReserve) _percentage -= withdrawalReserve; _writeOptions( _percentMultiply( IERC20(asset).balanceOf(address(this)) - currentReserves - obligatedFees, _percentage ), _oToken ); } /// @notice Burns away the oTokens to redeem the asset collateral /// @dev Operation to burn away the oTOkens in redemption of the asset collateral /// @param _amount Amount of calls to burn function burnOptions(uint256 _amount) external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount > IERC20(oToken).balanceOf(address(this))) revert Invalid(); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](2); uint256 normalizedAmount = _normalize(_amount, 8, 18); actions[0] = Actions.ActionArgs( Actions.ActionType.BurnShortOption, address(this), address(this), oToken, currentVaultId, _amount, 0, "" ); actions[1] = Actions.ActionArgs( Actions.ActionType.WithdrawCollateral, address(this), address(this), asset, currentVaultId, normalizedAmount, 0, "" ); IController controller = IController(addressBook.getController()); controller.operate(actions); collateralAmount -= normalizedAmount; if(collateralAmount == 0 && IERC20(oToken).balanceOf(address(this)) == 0) { // Withdrawal window reopens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; oToken = address(0); emit WithdrawalWindowActivated(withdrawalWindowExpires); } emit OptionsBurned(_amount); } /// @notice Operation to sell calls to an EXISTING order on AirSwap /// @dev Sells calls via AirSwap that exists by the counterparty /// @param _amount Amount of calls to sell to the exchange /// @param _premiumAmount Token amount to receive of the premium /// @param _otherParty Address of the counterparty /// @param _nonce Other party's AirSwap nonce function sellOptions(uint256 _amount, uint256 _premiumAmount, address _otherParty, uint256 _nonce) external onlyManager nonReentrant() whenNotPaused() { _sellOptions(_amount, _premiumAmount, _otherParty, _nonce); } /// @notice Operation to sell calls to an EXISTING order on AirSwap (via off-chain signature) /// @dev Sells calls via AirSwap that exists by the counterparty grabbed off-chain /// @param _order AirSwap order details function sellOptions(Types.Order memory _order) external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); _sellOptions(_order); } /// @notice Operation to both write AND sell options /// @dev Operation that can handle both the `writeOptions()` and `sellCalls()` at the same time /// @param _amount Amount of the asset token to collateralize the option /// @param _oToken Address of the oToken to write with /// @param _premiumAmount Amount of the oTokens to sell /// @param _otherParty address of the counterparty via AirSwap /// @param _nonce other party's AirSwap nonce function writeAndSellOptions( uint256 _amount, address _oToken, uint256 _premiumAmount, address _otherParty, uint256 _nonce ) external onlyManager nonReentrant() whenNotPaused() { uint256 oTokenPrevBal = IERC20(_oToken).balanceOf(address(this)); _writeOptions( _amount, _oToken ); _sellOptions( IERC20(_oToken).balanceOf(address(this)) - oTokenPrevBal, // This should NEVER underflow _premiumAmount, _otherParty, _nonce ); } /// @notice Operation to both write AND sell options /// @dev Operation that can handle both the `writeOptions()` and `sellCalls()` at the same time /// @param _percentage Percentage of the available asset tokens to write and sell /// @param _oToken Address of the oToken to write with /// @param _premiumAmount Amount of the oTokens to sell /// @param _otherParty address of the counterparty via AirSwap /// @param _nonce other party's AirSwap nonce function writeAndSellOptions( uint16 _percentage, address _oToken, uint256 _premiumAmount, address _otherParty, uint256 _nonce ) external onlyManager nonReentrant() whenNotPaused() { uint256 oTokenPrevBal = IERC20(_oToken).balanceOf(address(this)); _writeOptions( _percentMultiply( IERC20(asset).balanceOf(address(this)) - obligatedFees, _percentage ), _oToken ); _sellOptions( IERC20(_oToken).balanceOf(address(this)) - oTokenPrevBal, // This should NEVER underflow _premiumAmount, _otherParty, _nonce ); } /// @notice Operation to settle the vault /// @dev Settles the currently open vault and opens the withdrawal window function settleVault() external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); IController controller = IController(addressBook.getController()); // Check if ready to settle otherwise revert if(!controller.isSettlementAllowed(oToken)) revert SettlementNotReady(); // Settle the vault if ready Actions.ActionArgs[] memory action = new Actions.ActionArgs[](1); action[0] = Actions.ActionArgs( Actions.ActionType.SettleVault, address(this), address(this), address(0), currentVaultId, IERC20(oToken).balanceOf(address(this)), 0, "" ); controller.operate(action); // Withdrawal window opens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; collateralAmount = 0; oToken = address(0); currentReserves = 0; emit WithdrawalWindowActivated(withdrawalWindowExpires); } function _writeOptions(uint256 _amount, address _oToken) internal { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount == 0 || _oToken == address(0)) revert Invalid(); if(_amount > IERC20(asset).balanceOf(address(this)) - obligatedFees) revert NotEnoughFunds(); if(_oToken != oToken && oToken != address(0)) revert oTokenNotCleared(); // Calculate reserves if not already done if(oToken == address(0)) _calculateAndSetReserves(); // Check if the _amount exceeds the reserves if(_amount > IERC20(asset).balanceOf(address(this)) - obligatedFees - currentReserves) revert NotEnoughFunds_ReserveViolation(); Actions.ActionArgs[] memory actions; GammaTypes.Vault memory vault; IController controller = IController(addressBook.getController()); // Check if the vault is even open and open if no vault is open vault = controller.getVault(address(this), currentVaultId); if( vault.shortOtokens.length == 0 && vault.collateralAssets.length == 0 ) { actions = new Actions.ActionArgs[](3); currentVaultId = controller.getAccountVaultCounter(address(this)) + 1; actions[0] = Actions.ActionArgs( Actions.ActionType.OpenVault, address(this), address(this), address(0), currentVaultId, 0, 0, "" ); } else { actions = new Actions.ActionArgs[](2); } // Deposit _amount of asset to the vault actions[actions.length - 2] = Actions.ActionArgs( Actions.ActionType.DepositCollateral, address(this), address(this), asset, currentVaultId, _amount, 0, "" ); // Determine the amount of options to write uint256 oTokensToWrite; if(OtokenInterface(_oToken).isPut()) { oTokensToWrite = _normalize(_amount, ERC20(asset).decimals(), 14) / OtokenInterface(_oToken).strikePrice(); } else { oTokensToWrite = _normalize(_amount, ERC20(asset).decimals(), 8); } // Write options actions[actions.length - 1] = Actions.ActionArgs( Actions.ActionType.MintShortOption, address(this), address(this), _oToken, currentVaultId, oTokensToWrite, 0, "" ); // Approve the tokens to be moved IERC20(asset).approve(addressBook.getMarginPool(), _amount); // Submit the operations to the controller contract controller.operate(actions); collateralAmount += _amount; if(oToken != _oToken) oToken = _oToken; emit OptionsMinted(_amount, oToken, controller.getAccountVaultCounter(address(this))); } function _sellOptions(Types.Order memory _order) internal { } function _sellOptions(uint256 _amount, uint256 _premiumAmount, address _otherParty, uint256 _nonce) internal { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount > IERC20(oToken).balanceOf(address(this)) || oToken == address(0)) revert Invalid(); if(!ISwap(factory.airswapExchange()).signerAuthorizations(_otherParty, address(this))) revert Unauthorized_COUNTERPARTY_DID_NOT_SIGN(); // Prepare the AirSwap order Types.Order memory sellOrder; Types.Party memory signer; Types.Party memory sender; // Prepare the signer Types.Party portion (counterparty) of the order signer.kind = 0x36372b07; // ERC20_INTERFACE_ID signer.wallet = _otherParty; signer.token = asset; signer.amount = _premiumAmount; // Prepare the sender Types.Party portion (this contract) of the order sender.kind = 0x36372b07; // ERC20_INTERFACE_ID sender.token = oToken; sender.amount = _amount; // Define Types.Order sellOrder.nonce = _nonce; sellOrder.expiry = block.timestamp + 1 days; sellOrder.signer = signer; sellOrder.sender = sender; // Approve IERC20(oToken).approve(factory.airswapExchange(), _amount); ISwap(factory.airswapExchange()).swap(sellOrder); // Calculate performance fee obligatedFees += _percentMultiply(_premiumAmount, performanceFee); emit OptionsSold(_amount, _premiumAmount); } function _calculateAndSetReserves() internal { currentReserves = _percentMultiply(IERC20(asset).balanceOf(address(this)) - obligatedFees, withdrawalReserve); } function _onlyManager() internal view { if(msg.sender != manager) revert Unauthorized(); } function _normalize( uint256 _valueToNormalize, uint256 _valueDecimal, uint256 _normalDecimals ) internal pure returns (uint256) { int256 decimalDiff = int256(_valueDecimal) - int256(_normalDecimals); if(decimalDiff > 0) { return _valueToNormalize / (10**uint256(decimalDiff)); } else if(decimalDiff < 0) { return _valueToNormalize * 10**uint256(-decimalDiff); } else { return _valueToNormalize; } } function _withdrawalWindowCheck(bool _revertIfClosed) internal view returns(bool isActive) { if(block.timestamp > withdrawalWindowExpires && _revertIfClosed) revert WithdrawalWindowNotActive(); return block.timestamp > withdrawalWindowExpires; } function _percentMultiply(uint256 _subtotal, uint16 _fee) internal pure returns(uint256) { return _subtotal * _fee / 10000; } }
@notice Allows the manager to collect fees @dev Transfers all of the obligatedFees to the manager and sets it to zero
function sweepFees() external onlyManager nonReentrant() whenNotPaused() { IERC20(asset).safeTransfer(msg.sender, obligatedFees); obligatedFees = 0; }
5,355,593
[ 1, 19132, 326, 3301, 358, 3274, 1656, 281, 225, 2604, 18881, 777, 434, 326, 320, 31627, 690, 2954, 281, 358, 326, 3301, 471, 1678, 518, 358, 3634, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 17462, 2954, 281, 1435, 3903, 1338, 1318, 1661, 426, 8230, 970, 1435, 1347, 1248, 28590, 1435, 288, 203, 3639, 467, 654, 39, 3462, 12, 9406, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 320, 31627, 690, 2954, 281, 1769, 203, 3639, 320, 31627, 690, 2954, 281, 273, 374, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/7700/0x4BC97bCb77f7Ff9D3540e754E4cBA9EFF5f6cc66/sources/lib/solady/src/utils/Base64.sol
@dev Encodes `data` using the base64 encoding described in RFC 4648. Equivalent to `encode(data, fileSafe, false)`.
function encode(bytes memory data, bool fileSafe) internal pure returns (string memory result) { result = encode(data, fileSafe, false); }
4,654,702
[ 1, 19771, 1375, 892, 68, 1450, 326, 1026, 1105, 2688, 11893, 316, 8372, 1059, 27382, 18, 31208, 358, 1375, 3015, 12, 892, 16, 585, 9890, 16, 629, 13, 8338, 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, 445, 2017, 12, 3890, 3778, 501, 16, 1426, 585, 9890, 13, 2713, 16618, 1135, 261, 1080, 3778, 563, 13, 288, 203, 3639, 563, 273, 2017, 12, 892, 16, 585, 9890, 16, 629, 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 ]
./full_match/43113/0x5509Ce9beB6A9C2A61f51CfD81DD3A5fd20a29bC/sources/contracts/AaveStrategy.sol
* @title Aave strategy for AVAX @dev No need to _enterMarket() as LendingPool already defaults collateral to true./ address _rewardController, 0 address _tokenDelegator, 1 address _avToken, 2 address _avDebtToken, 3 address _timelock, 4 address[5] memory addressesArray, uint256 _leverageLevel, 0 uint256 _safetyFactor, 1 uint256 _leverageBips, 2 uint256 _minMinting, 3 uint256 _minTokensToReinvest, 4 uint256[5] memory uintArray, uint256[3] memory _fees, fees[0] performanceFee , fees[1] adminFee , fees[2] devFees uint256 _reinvestRewardBips
contract AaveStrategyAvaxV1 is BlizzardStrategyV2Payable, ReentrancyGuard { using SafeMath for uint256; IAaveIncentivesController private rewardController; ILendingPool private tokenDelegator; IWAVAX private constant WAVAX = IWAVAX(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); uint256 private leverageLevel; uint256 private safetyFactor; uint256 private leverageBips; uint256 private minMinting; address private avToken; address private avDebtToken; constructor( string memory _name ) { name = _name; devAddr = 0xb686a81F32D9c22e29315075dF64a390ba3Fe83C; adminAddr = 0x6587D861B7cEa89E0E78AE4897a1A757bB40Cee5; emit Reinvest(0, 0); } function initializeAddresses( ) external { rewardController = IAaveIncentivesController(_rewardController); tokenDelegator = ILendingPool(_tokenDelegator); transferOwnership(_timelock); } function initializeNumbers( uint256 _reinvestRewardBips ) external { _updateLeverage( ); setAllowances(); updateReinvestReward(_reinvestRewardBips); } function initializeFees(uint256 _fee1,uint256 _fee2,uint256 _fee3) external { updatePerformanceFee(_fee1); updateAdminFee(_fee2); updateDevFee(_fee3); updateDepositsEnabled(true); } function _getAccountData() internal view returns ( uint256 balance, uint256 borrowed, uint256 borrowable ) { balance = IERC20(avToken).balanceOf(address(this)); borrowed = IERC20(avDebtToken).balanceOf(address(this)); borrowable = 0; if ( balance.mul(leverageLevel.sub(leverageBips)).div(leverageLevel) > borrowed ) { borrowable = balance .mul(leverageLevel.sub(leverageBips)) .div(leverageLevel) .sub(borrowed); } } function _getAccountData() internal view returns ( uint256 balance, uint256 borrowed, uint256 borrowable ) { balance = IERC20(avToken).balanceOf(address(this)); borrowed = IERC20(avDebtToken).balanceOf(address(this)); borrowable = 0; if ( balance.mul(leverageLevel.sub(leverageBips)).div(leverageLevel) > borrowed ) { borrowable = balance .mul(leverageLevel.sub(leverageBips)) .div(leverageLevel) .sub(borrowed); } } receive() external payable { require(msg.sender == address(WAVAX), "not allowed"); } function totalDeposits() public view override returns (uint256) { (uint256 balance, uint256 borrowed, ) = _getAccountData(); return balance.sub(borrowed); } function _updateLeverage( uint256 _leverageLevel, uint256 _safetyFactor, uint256 _minMinting, uint256 _leverageBips ) internal { leverageLevel = _leverageLevel; leverageBips = _leverageBips; safetyFactor = _safetyFactor; minMinting = _minMinting; } function updateLeverage( uint256 _leverageLevel, uint256 _safetyFactor, uint256 _minMinting, uint256 _leverageBips ) external onlyDev { _updateLeverage( _leverageLevel, _safetyFactor, _minMinting, _leverageBips ); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); _rollupDebt(); } function setAllowances() public override onlyOwner { WAVAX.approve(address(tokenDelegator), type(uint256).max); IERC20(avToken).approve(address(tokenDelegator), type(uint256).max); } function deposit() external payable override nonReentrant { _deposit(msg.sender, msg.value); } WAVAX.deposit{value: msg.value}(); function depositFor(address account) external payable override nonReentrant { _deposit(account, msg.value); } WAVAX.deposit{value: msg.value}(); function deposit(uint256 amount) external override { revert(); } function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { revert(); } function depositFor(address account, uint256 amount) external override { revert(); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function _deposit(address account, uint256 amount) private onlyAllowedDeposits { require(DEPOSITS_ENABLED == true, "AaveStrategyAvaxV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { uint256 avaxRewards = _checkRewards(); if (avaxRewards > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(avaxRewards); } } _mint(account, getSharesForDepositTokens(amount)); _stakeDepositTokens(amount); emit Deposit(account, amount); } function withdraw(uint256 amount) external override nonReentrant { uint256 WAVAXAmount = totalDeposits().mul(amount).div(totalSupply); require( WAVAXAmount > minMinting, "AaveStrategyAvaxV1::below minimum withdraw" ); if (WAVAXAmount > 0) { _burn(msg.sender, amount); uint256 avaxAmount = _withdrawDepositTokens(WAVAXAmount); require(success, "AaveStrategyAvaxV1::transfer failed"); emit Withdraw(msg.sender, avaxAmount); } } function withdraw(uint256 amount) external override nonReentrant { uint256 WAVAXAmount = totalDeposits().mul(amount).div(totalSupply); require( WAVAXAmount > minMinting, "AaveStrategyAvaxV1::below minimum withdraw" ); if (WAVAXAmount > 0) { _burn(msg.sender, amount); uint256 avaxAmount = _withdrawDepositTokens(WAVAXAmount); require(success, "AaveStrategyAvaxV1::transfer failed"); emit Withdraw(msg.sender, avaxAmount); } } (bool success, ) = msg.sender.call{value: avaxAmount}(""); function _withdrawDepositTokens(uint256 amount) private returns (uint256) { _unrollDebt(amount); (uint256 balance, , ) = _getAccountData(); if (amount > balance) { amount = type(uint256).max; } uint256 withdrawn = tokenDelegator.withdraw( address(WAVAX), amount, address(this) ); WAVAX.withdraw(withdrawn); _rollupDebt(); return withdrawn; } function _withdrawDepositTokens(uint256 amount) private returns (uint256) { _unrollDebt(amount); (uint256 balance, , ) = _getAccountData(); if (amount > balance) { amount = type(uint256).max; } uint256 withdrawn = tokenDelegator.withdraw( address(WAVAX), amount, address(this) ); WAVAX.withdraw(withdrawn); _rollupDebt(); return withdrawn; } function reinvest() external override onlyEOA nonReentrant { uint256 avaxRewards = _checkRewards(); require( avaxRewards >= MIN_TOKENS_TO_REINVEST, "AaveStrategyAvaxV1::reinvest" ); _reinvest(avaxRewards); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), adminAddr, adminFee); } uint256 performanceFee = amount.mul(PERFORMANCE_FEE_BIPS).div( BIPS_DIVISOR ); if (performanceFee > 0) { _safeTransfer(address(rewardToken), owner(), performanceFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div( BIPS_DIVISOR ); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens( amount.sub(performanceFee).sub(devFee).sub(adminFee).sub( reinvestFee ) ); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), adminAddr, adminFee); } uint256 performanceFee = amount.mul(PERFORMANCE_FEE_BIPS).div( BIPS_DIVISOR ); if (performanceFee > 0) { _safeTransfer(address(rewardToken), owner(), performanceFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div( BIPS_DIVISOR ); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens( amount.sub(performanceFee).sub(devFee).sub(adminFee).sub( reinvestFee ) ); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), adminAddr, adminFee); } uint256 performanceFee = amount.mul(PERFORMANCE_FEE_BIPS).div( BIPS_DIVISOR ); if (performanceFee > 0) { _safeTransfer(address(rewardToken), owner(), performanceFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div( BIPS_DIVISOR ); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens( amount.sub(performanceFee).sub(devFee).sub(adminFee).sub( reinvestFee ) ); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), adminAddr, adminFee); } uint256 performanceFee = amount.mul(PERFORMANCE_FEE_BIPS).div( BIPS_DIVISOR ); if (performanceFee > 0) { _safeTransfer(address(rewardToken), owner(), performanceFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div( BIPS_DIVISOR ); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens( amount.sub(performanceFee).sub(devFee).sub(adminFee).sub( reinvestFee ) ); emit Reinvest(totalDeposits(), totalSupply); } function _reinvest(uint256 amount) private { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; rewardController.claimRewards(assets, amount, address(this)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 adminFee = amount.mul(ADMIN_FEE_BIPS).div(BIPS_DIVISOR); if (adminFee > 0) { _safeTransfer(address(rewardToken), adminAddr, adminFee); } uint256 performanceFee = amount.mul(PERFORMANCE_FEE_BIPS).div( BIPS_DIVISOR ); if (performanceFee > 0) { _safeTransfer(address(rewardToken), owner(), performanceFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div( BIPS_DIVISOR ); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } _stakeDepositTokens( amount.sub(performanceFee).sub(devFee).sub(adminFee).sub( reinvestFee ) ); emit Reinvest(totalDeposits(), totalSupply); } function _rollupDebt() internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(WAVAX), borrowable, 0, address(this) ); tokenDelegator.deposit( address(WAVAX), borrowable, address(this), 0 ); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(WAVAX), borrowable, 0, address(this) ); tokenDelegator.deposit( address(WAVAX), borrowable, address(this), 0 ); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(WAVAX), borrowable, 0, address(this) ); tokenDelegator.deposit( address(WAVAX), borrowable, address(this), 0 ); (balance, borrowed, borrowable) = _getAccountData(); } } function _rollupDebt() internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 lendTarget = balance .sub(borrowed) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips); while (balance < lendTarget) { if (balance.add(borrowable) > lendTarget) { borrowable = lendTarget.sub(balance); } if (borrowable < minMinting) { break; } tokenDelegator.borrow( address(WAVAX), borrowable, 0, address(this) ); tokenDelegator.deposit( address(WAVAX), borrowable, address(this), 0 ); (balance, borrowed, borrowable) = _getAccountData(); } } function _unrollDebt(uint256 amountToFreeUp) internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw( address(WAVAX), unrollAmount, address(this) ); tokenDelegator.repay( address(WAVAX), unrollAmount, 2, address(this) ); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw( address(WAVAX), unrollAmount, address(this) ); tokenDelegator.repay( address(WAVAX), unrollAmount, 2, address(this) ); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw( address(WAVAX), unrollAmount, address(this) ); tokenDelegator.repay( address(WAVAX), unrollAmount, 2, address(this) ); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _unrollDebt(uint256 amountToFreeUp) internal { ( uint256 balance, uint256 borrowed, uint256 borrowable ) = _getAccountData(); uint256 targetBorrow = balance .sub(borrowed) .sub(amountToFreeUp) .mul(leverageLevel.sub(safetyFactor)) .div(leverageBips) .sub(balance.sub(borrowed).sub(amountToFreeUp)); uint256 toRepay = borrowed.sub(targetBorrow); while (toRepay > 0) { uint256 unrollAmount = borrowable; if (unrollAmount > borrowed) { unrollAmount = borrowed; } tokenDelegator.withdraw( address(WAVAX), unrollAmount, address(this) ); tokenDelegator.repay( address(WAVAX), unrollAmount, 2, address(this) ); (balance, borrowed, borrowable) = _getAccountData(); if (targetBorrow >= borrowed) { break; } toRepay = borrowed.sub(targetBorrow); } } function _stakeDepositTokens(uint256 amount) private { require(amount > 0, "AaveStrategyAvaxV1::_stakeDepositTokens"); tokenDelegator.deposit(address(WAVAX), amount, address(this), 0); _rollupDebt(); } function _safeTransfer( address token, address to, uint256 value ) private { require( IERC20(token).transfer(to, value), "AaveStrategyAvaxV1::TRANSFER_FROM_FAILED" ); } function _checkRewards() internal view returns (uint256 avaxAmount) { address[] memory assets = new address[](2); assets[0] = avToken; assets[1] = avDebtToken; return rewardController.getRewardsBalance(assets, address(this)); } function checkReward() public view override returns (uint256) { return _checkRewards(); } function getActualLeverage() public view returns (uint256) { (uint256 balance, uint256 borrowed, ) = _getAccountData(); return balance.mul(1e18).div(balance.sub(borrowed)); } function estimateDeployedBalance() external view override returns (uint256) { return totalDeposits(); } function rescueDeployedFunds( uint256 minReturnAmountAccepted, bool disableDeposits ) external override onlyOwner { uint256 balanceBefore = WAVAX.balanceOf(address(this)); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); tokenDelegator.withdraw( address(WAVAX), type(uint256).max, address(this) ); uint256 balanceAfter = WAVAX.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "AaveStrategyAvaxV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } function rescueDeployedFunds( uint256 minReturnAmountAccepted, bool disableDeposits ) external override onlyOwner { uint256 balanceBefore = WAVAX.balanceOf(address(this)); (uint256 balance, uint256 borrowed, ) = _getAccountData(); _unrollDebt(balance.sub(borrowed)); tokenDelegator.withdraw( address(WAVAX), type(uint256).max, address(this) ); uint256 balanceAfter = WAVAX.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "AaveStrategyAvaxV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } }
13,173,168
[ 1, 37, 836, 6252, 364, 15068, 2501, 225, 2631, 1608, 358, 389, 2328, 3882, 278, 1435, 487, 511, 2846, 2864, 1818, 3467, 4508, 2045, 287, 358, 638, 18, 19, 225, 1758, 389, 266, 2913, 2933, 16, 4202, 374, 225, 1758, 389, 2316, 15608, 639, 16, 540, 404, 225, 1758, 389, 842, 1345, 16, 7734, 576, 225, 1758, 389, 842, 758, 23602, 1345, 16, 5411, 890, 225, 1758, 389, 8584, 292, 975, 16, 9079, 1059, 1758, 63, 25, 65, 3778, 6138, 1076, 16, 225, 2254, 5034, 389, 298, 5682, 2355, 16, 1850, 374, 225, 2254, 5034, 389, 87, 1727, 14369, 6837, 16, 6647, 404, 225, 2254, 5034, 389, 298, 5682, 38, 7146, 16, 6647, 576, 225, 2254, 5034, 389, 1154, 49, 474, 310, 16, 2398, 890, 225, 2254, 5034, 389, 1154, 5157, 774, 426, 5768, 395, 16, 565, 1059, 2254, 5034, 63, 25, 65, 3778, 2254, 1076, 16, 2254, 5034, 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, 16351, 432, 836, 4525, 3769, 651, 58, 21, 353, 8069, 25695, 1060, 4525, 58, 22, 9148, 429, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 37, 836, 382, 2998, 3606, 2933, 3238, 19890, 2933, 31, 203, 565, 467, 48, 2846, 2864, 3238, 1147, 15608, 639, 31, 203, 565, 467, 59, 5856, 2501, 3238, 5381, 678, 5856, 2501, 273, 203, 3639, 467, 59, 5856, 2501, 12, 20, 20029, 6938, 74, 6028, 5284, 23, 39, 21, 73, 27, 7140, 23, 4449, 42, 6840, 5877, 37, 21, 38, 5608, 41, 5324, 70, 7140, 16894, 6028, 71, 27, 1769, 203, 565, 2254, 5034, 3238, 884, 5682, 2355, 31, 203, 565, 2254, 5034, 3238, 24179, 6837, 31, 203, 565, 2254, 5034, 3238, 884, 5682, 38, 7146, 31, 203, 565, 2254, 5034, 3238, 1131, 49, 474, 310, 31, 203, 565, 1758, 3238, 1712, 1345, 31, 203, 565, 1758, 3238, 1712, 758, 23602, 1345, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 203, 203, 565, 262, 288, 203, 3639, 508, 273, 389, 529, 31, 203, 203, 3639, 4461, 3178, 273, 374, 6114, 26, 5292, 69, 11861, 42, 1578, 40, 29, 71, 3787, 73, 5540, 6938, 3361, 5877, 72, 42, 1105, 69, 5520, 20, 12124, 23, 2954, 10261, 39, 31, 203, 3639, 3981, 3178, 273, 374, 92, 26, 8204, 27, 40, 5292, 21, 38, 27, 71, 41, 69, 6675, 41, 20, 41, 8285, 16985, 24, 6675, 27, 69, 21, 37, 5877, 27, 70, 38, 7132, 39, 1340, 2 ]
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.
Time that must elapse between rounds. [NOT MVP]
uint timelock;
12,594,513
[ 1, 950, 716, 1297, 415, 28933, 3086, 21196, 18, 306, 4400, 25324, 52, 65, 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, 1658, 292, 975, 31, 4202, 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; /// @title A facet of CSportsCore that holds all important constants and modifiers /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsConstants { /// @dev The maximum # of marketing tokens that can ever be created /// by the commissioner. uint16 public MAX_MARKETING_TOKENS = 2500; /// @dev The starting price for commissioner auctions (if the average /// of the last 2 is less than this, we will use this value) /// A finney is 1/1000 of an ether. uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby /// @dev The duration of commissioner auctions uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing; /// @dev Number of seconds in a week uint32 constant WEEK_SECS = 1 weeks; } /// @title A facet of CSportsCore that manages an individual&#39;s authorized role against access privileges. /// @author CryptoSports, Inc. (https://cryptosports.team)) /// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged. contract CSportsAuth is CSportsConstants { // This facet controls access control for CryptoSports. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the CSportsCore constructor. // // - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts. // // - The COO: The COO can perform administrative functions. // // - The Commisioner can perform "oracle" functions like adding new real world players, // setting players active/inactive, and scoring contests. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); /// The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; address public commissionerAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Flag that identifies whether or not we are in development and should allow development /// only functions to be called. bool public isDevelopment = true; /// @dev Access modifier to allow access to development mode functions modifier onlyUnderDevelopment() { require(isDevelopment == true); _; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Access modifier for Commissioner-only functionality modifier onlyCommissioner() { require(msg.sender == commissionerAddress); _; } /// @dev Requires any one of the C level addresses modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == commissionerAddress ); _; } /// @dev prevents contracts from hitting the method modifier notContract() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0); _; } /// @dev One way switch to set the contract into prodution mode. This is one /// way in that the contract can never be set back into development mode. Calling /// this function will block all future calls to functions that are meant for /// access only while we are under development. It will also enable more strict /// additional checking on various parameters and settings. function setProduction() public onlyCEO onlyUnderDevelopment { isDevelopment = false; } /// @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 { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) public onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO. /// @param _newCommissioner The address of the new COO function setCommissioner(address _newCommissioner) public onlyCEO { require(_newCommissioner != address(0)); commissionerAddress = _newCommissioner; } /// @dev Assigns all C-Level addresses /// @param _ceo CEO address /// @param _cfo CFO address /// @param _coo COO address /// @param _commish Commissioner address function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO { require(_ceo != address(0)); require(_cfo != address(0)); require(_coo != address(0)); require(_commish != address(0)); ceoAddress = _ceo; cfoAddress = _cfo; cooAddress = _coo; commissionerAddress = _commish; } /// @dev Transfers the balance of this contract to the CFO function withdrawBalance() external onlyCFO { cfoAddress.transfer(address(this).balance); } /*** 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 Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() public onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. function unpause() public onlyCEO whenPaused { paused = false; } } /// @dev Interface required by league roster contract to access /// the mintPlayers(...) function interface CSportsMinter { /// @dev Called by league roster contract as a sanity check function isMinter() external pure returns (bool); /// @dev The method called by the league roster contract to mint a new player and create its commissioner auction function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) external; } /// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster /// contract. Also referenced by CSportsCore. /// @author CryptoSports, Inc. (http://cryptosports.team) contract CSportsRosterPlayer { struct RealWorldPlayer { // The player&#39;s certified identification. This is the md5 hash of // {player&#39;s last name}-{player&#39;s first name}-{player&#39;s birthday in YYYY-MM-DD format}-{serial number} // where the serial number is usually 0, but gives us an ability to deal with making // sure all MD5s are unique. uint128 md5Token; // Stores the average sale price of the most recent 2 commissioner sales uint128 prevCommissionerSalePrice; // The last time this real world player was minted. uint64 lastMintedTime; // The number of PlayerTokens minted for this real world player uint32 mintedCount; // When true, there is an active auction for this player owned by // the commissioner (indicating a gen0 minting auction is in progress) bool hasActiveCommissionerAuction; // Indicates this real world player can be actively minted bool mintingEnabled; // Any metadata we want to attach to this player (in JSON format) string metadata; } } /// @title Contract that holds all of the real world player data. This data is /// added by the commissioner and represents an on-blockchain database of /// players in the league. /// @author CryptoSports, Inc. (http://cryptosports.team) contract CSportsLeagueRoster is CSportsAuth, CSportsRosterPlayer { /*** STORAGE ***/ /// @dev Holds the coreContract which supports the CSportsMinter interface CSportsMinter public minterContract; /// @dev Holds one entry for each real-world player available in the /// current league (e.g. NFL). There can be a maximum of 4,294,967,295 /// entries in this array (plenty) because it is indexed by a uint32. /// This structure is constantly updated by a commissioner. If the /// realWorldPlayer[<whatever].mintingEnabled property is true, then playerTokens /// tied to this realWorldPlayer entry will automatically be minted. RealWorldPlayer[] public realWorldPlayers; mapping (uint128 => uint32) public md5TokenToRosterIndex; /*** MODIFIERS ***/ /// @dev Access modifier for core contract only functions modifier onlyCoreContract() { require(msg.sender == address(minterContract)); _; } /*** FUNCTIONS ***/ /// @dev Contract constructor. All "C" level authorized addresses /// are set to the contract creator. constructor() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; commissionerAddress = msg.sender; } /// @dev Sanity check that identifies this contract is a league roster contract function isLeagueRosterContract() public pure returns (bool) { return true; } /// @dev Returns the full player structure from the league roster contract given its index. /// @param idx Index of player we are interested in function realWorldPlayerFromIndex(uint128 idx) public view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled) { RealWorldPlayer memory _rwp; _rwp = realWorldPlayers[idx]; md5Token = _rwp.md5Token; prevCommissionerSalePrice = _rwp.prevCommissionerSalePrice; lastMintedTime = _rwp.lastMintedTime; mintedCount = _rwp.mintedCount; hasActiveCommissionerAuction = _rwp.hasActiveCommissionerAuction; mintingEnabled = _rwp.mintingEnabled; } /// @dev Sets the coreContractAddress that will restrict access /// to certin functions function setCoreContractAddress(address _address) public onlyCEO { CSportsMinter candidateContract = CSportsMinter(_address); // NOTE: verify that a contract is what we expect (not foolproof, just // a sanity check) require(candidateContract.isMinter()); // Set the new contract address minterContract = candidateContract; } /// @return uint32 count - # of entries in the realWorldPlayer array function playerCount() public view returns (uint32 count) { return uint32(realWorldPlayers.length); } /// @dev Creates and adds realWorldPlayer entries, and mints a new ERC721 token for each, and puts each on /// auction as a commissioner auction. /// @param _md5Tokens The MD5s to be associated with the roster entries we are adding /// @param _mintingEnabled An array (of equal length to _md5Tokens) indicating the minting status of that player /// (if an entry is not true, that player will not be minted and no auction created) /// @param _startPrice The starting price for the auction we will create for the newly minted token /// @param _endPrice The ending price for the auction we will create for the newly minted token /// @param _duration The duration for the auction we will create for the newly minted token function addAndMintPlayers(uint128[] _md5Tokens, bool[] _mintingEnabled, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public onlyCommissioner { // Add the real world players to the roster addRealWorldPlayers(_md5Tokens, _mintingEnabled); // Mint the newly added players and create commissioner auctions minterContract.mintPlayers(_md5Tokens, _startPrice, _endPrice, _duration); } /// @dev Creates and adds a RealWorldPlayer entry. /// @param _md5Tokens - An array of MD5 tokens for players to be added to our realWorldPlayers array. /// @param _mintingEnabled - An array (of equal length to _md5Tokens) indicating the minting status of that player function addRealWorldPlayers(uint128[] _md5Tokens, bool[] _mintingEnabled) public onlyCommissioner { if (_md5Tokens.length != _mintingEnabled.length) { revert(); } for (uint32 i = 0; i < _md5Tokens.length; i++) { // We won&#39;t try to put an md5Token duplicate by using the md5TokenToRosterIndex // mapping (notice we need to deal with the fact that a non-existent mapping returns 0) if ( (realWorldPlayers.length == 0) || ((md5TokenToRosterIndex[_md5Tokens[i]] == 0) && (realWorldPlayers[0].md5Token != _md5Tokens[i])) ) { RealWorldPlayer memory _realWorldPlayer = RealWorldPlayer({ md5Token: _md5Tokens[i], prevCommissionerSalePrice: 0, lastMintedTime: 0, mintedCount: 0, hasActiveCommissionerAuction: false, mintingEnabled: _mintingEnabled[i], metadata: "" }); uint256 _rosterIndex = realWorldPlayers.push(_realWorldPlayer) - 1; // It&#39;s probably never going to happen, but just in case, we need // to make sure our realWorldPlayers can be indexed by a uint32 require(_rosterIndex < 4294967295); // Map the md5Token to its rosterIndex md5TokenToRosterIndex[_md5Tokens[i]] = uint32(_rosterIndex); } } } /// @dev Sets the metadata for a real world player token that has already been added. /// @param _md5Token The MD5 key of the token to update /// @param _metadata The JSON string representing the metadata for the token function setMetadata(uint128 _md5Token, string _metadata) public onlyCommissioner { uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token]; if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) { // Valid MD5 token realWorldPlayers[_rosterIndex].metadata = _metadata; } } /// @dev Returns the metadata for a specific token /// @param _md5Token MD5 key for token we want the metadata for function getMetadata(uint128 _md5Token) public view returns (string metadata) { uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token]; if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) { // Valid MD5 token metadata = realWorldPlayers[_rosterIndex].metadata; } else { metadata = ""; } } /// @dev Function to remove a particular md5Token from our array of players. This function /// will be blocked after we are completed with development. Deleting entries would /// screw up the ids of realWorldPlayers held by the core contract&#39;s playerTokens structure. /// @param _md5Token - The MD5 token of the entry to remove. function removeRealWorldPlayer(uint128 _md5Token) public onlyCommissioner onlyUnderDevelopment { for (uint32 i = 0; i < uint32(realWorldPlayers.length); i++) { RealWorldPlayer memory player = realWorldPlayers[i]; if (player.md5Token == _md5Token) { uint32 stopAt = uint32(realWorldPlayers.length - 1); for (uint32 j = i; j < stopAt; j++){ realWorldPlayers[j] = realWorldPlayers[j+1]; md5TokenToRosterIndex[realWorldPlayers[j].md5Token] = j; } delete realWorldPlayers[realWorldPlayers.length-1]; realWorldPlayers.length--; break; } } } /// @dev Returns TRUE if there is an open commissioner auction for a realWorldPlayer /// @param _md5Token - md5Token of the player of interest function hasOpenCommissionerAuction(uint128 _md5Token) public view onlyCommissioner returns (bool) { uint128 _rosterIndex = this.getRealWorldPlayerRosterIndex(_md5Token); if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) { revert(); } else { return realWorldPlayers[_rosterIndex].hasActiveCommissionerAuction; } } /// @dev Returns the rosterId of the player identified with an md5Token /// @param _md5Token = md5Token of exisiting function getRealWorldPlayerRosterIndex(uint128 _md5Token) public view returns (uint128) { uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token]; if (_rosterIndex == 0) { // Deal with the fact that mappings return 0 for non-existent members and 0 is // a valid rosterIndex for the 0th (first) entry in the realWorldPlayers array. if ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token)) { return uint128(0); } } else { return uint128(_rosterIndex); } // Intentionally returning an invalid rosterIndex (too big) as an indicator that // the md5 passed was not found. return uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /// @dev Enables (or disables) minting for a particular real world player. /// @param _md5Tokens - The md5Token of the player to be updated /// @param _mintingEnabled - True to enable, false to disable minting for the player function enableRealWorldPlayerMinting(uint128[] _md5Tokens, bool[] _mintingEnabled) public onlyCommissioner { if (_md5Tokens.length != _mintingEnabled.length) { revert(); } for (uint32 i = 0; i < _md5Tokens.length; i++) { uint32 _rosterIndex = md5TokenToRosterIndex[_md5Tokens[i]]; if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Tokens[i]))) { // _rosterIndex is valid realWorldPlayers[_rosterIndex].mintingEnabled = _mintingEnabled[i]; } else { // Tried to enable/disable minting on non-existent realWorldPlayer revert(); } } } /// @dev Returns a boolean indicating whether or not a particular real world player is minting /// @param _md5Token - The player to look at function isRealWorldPlayerMintingEnabled(uint128 _md5Token) public view returns (bool) { // Have to deal with the fact that the 0th entry is a valid one. uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token]; if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) { // _rosterIndex is valid return realWorldPlayers[_rosterIndex].mintingEnabled; } else { // Tried to enable/disable minting on non-existent realWorldPlayer revert(); } } /// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be /// called by the core contract. /// @param _rosterIndex - Index into realWorldPlayers of the entry to change. /// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions /// @param _lastMintedTime - Time this real world player was last minted /// @param _mintedCount - The number of playerTokens that have been minted for this player /// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player /// @param _mintingEnabled - Denotes whether or not we should mint this real world player function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCoreContract { require(_rosterIndex < realWorldPlayers.length); RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex]; _realWorldPlayer.prevCommissionerSalePrice = _prevCommissionerSalePrice; _realWorldPlayer.lastMintedTime = _lastMintedTime; _realWorldPlayer.mintedCount = _mintedCount; _realWorldPlayer.hasActiveCommissionerAuction = _hasActiveCommissionerAuction; _realWorldPlayer.mintingEnabled = _mintingEnabled; } /// @dev Marks a real world player record as having an active commissioner auction. /// Will throw if there is hasActiveCommissionerAuction was already true upon entry. /// @param _rosterIndex - Index to the real world player record. function setHasCommissionerAuction(uint32 _rosterIndex) public onlyCoreContract { require(_rosterIndex < realWorldPlayers.length); RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex]; require(!_realWorldPlayer.hasActiveCommissionerAuction); _realWorldPlayer.hasActiveCommissionerAuction = true; } /// @param _rosterIndex - Index into our roster that we want to record the fact that there is /// no longer an active commissioner auction. /// @param _price - The price we want to record function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) public onlyCoreContract { require(_rosterIndex < realWorldPlayers.length); RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex]; require(_realWorldPlayer.hasActiveCommissionerAuction); if (_realWorldPlayer.prevCommissionerSalePrice == 0) { _realWorldPlayer.prevCommissionerSalePrice = _price; } else { _realWorldPlayer.prevCommissionerSalePrice = (_realWorldPlayer.prevCommissionerSalePrice + _price)/2; } _realWorldPlayer.hasActiveCommissionerAuction = false; // Finally, re-mint another player token for this realWorldPlayer and put him up for auction // at the default pricing and duration (auto mint) if (_realWorldPlayer.mintingEnabled) { uint128[] memory _md5Tokens = new uint128[](1); _md5Tokens[0] = _realWorldPlayer.md5Token; minterContract.mintPlayers(_md5Tokens, 0, 0, 0); } } /// @param _rosterIndex - Index into our roster that we want to record the fact that there is /// no longer an active commissioner auction. function commissionerAuctionCancelled(uint32 _rosterIndex) public view onlyCoreContract { require(_rosterIndex < realWorldPlayers.length); RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex]; require(_realWorldPlayer.hasActiveCommissionerAuction); // We do not clear the hasActiveCommissionerAuction bit on a cancel. This will // continue to block the minting of new commissioner tokens (limiting supply). // The only way this RWP can be back on a commissioner auction is by the commish // putting the token corresponding to the canceled auction back on auction. } }
@dev Contract constructor. All "C" level authorized addresses are set to the contract creator.
constructor() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; commissionerAddress = msg.sender; }
2,276,295
[ 1, 8924, 3885, 18, 4826, 315, 39, 6, 1801, 10799, 6138, 854, 444, 358, 326, 6835, 11784, 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 ]
[ 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, 225, 3885, 1435, 1071, 288, 203, 565, 276, 4361, 1887, 273, 1234, 18, 15330, 31, 203, 565, 276, 617, 1887, 273, 1234, 18, 15330, 31, 203, 565, 1825, 83, 1887, 273, 1234, 18, 15330, 31, 203, 565, 1543, 19710, 264, 1887, 273, 1234, 18, 15330, 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, -100, -100, -100, -100, -100, -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.3; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./ERC1155.sol"; import "./NFTSplitterStorage.sol"; import "./NFTSplitterAdmin.sol"; contract NFTSplitter is NFTSplitterStorage, ERC165, ERC1155, IERC1155Receiver, ReentrancyGuard { //base contract version uint8 public constant version = 1; //modifiers /** * @dev Modifier that checks that timestamp is greater than lock time * TODO: implement lock logic in contract modifier isNotLocked() { require(block.timestamp > lockEndDate, "NFTSplitter: Lock time is not over"); _; }*/ /** * @dev Modifier that checks that only the original NFT owner can execute the trx * */ modifier onlyOriginalNFTOwner() { require(originalOwner == msg.sender, "NFTSplitter: Only original NFT owner can execute this function"); _; } /** * @dev Modifier that checks that the original NFT owner is not executing the trx * */ modifier notOriginalNFTOwner() { require(originalOwner != msg.sender, "NFTSplitter: Original NFT owner is not allowed to execute this function" ); _; } /** * @dev Modifier that checks that all pieces are owned by the same address * */ modifier ownsAllPieces() { require(balanceOf(msg.sender, tokenId) == pieces, "NFTSplitter: you should own all pieces to withdraw the original NFT"); _; } /** * @dev emitted after split creation */ event NFTSplit( address indexed originalNFTAddress, uint indexed id, uint indexed pieces, uint price, uint percentage ); /** * @dev emitted when buyer buys a piece */ event NFTSplitSold( address indexed pieceOwner, address indexed buyer, uint indexed amount, uint price ); /** * @dev emitted when NFT owner buys a piece from buyer */ event NFTSplitBuyBack( address indexed originalNFTAddress, address indexed buyer, uint amount, uint price ); /** * @dev emitted when original NFT is withdrawn from contract */ event NFTWithdraw( address indexed originalNFTAddress, address indexed buyer ); /** * @dev constructor with initial name and symbol values */ constructor( ) ERC1155("") { name = "NFT Splitter"; symbol = "NFTS"; } event Log(string message); //no set uri function needed function setURI(string memory newuri) public{ revert(); } /** * @notice mint function not needed */ function mint( address account, uint256 id, uint256 amount, bytes memory data ) public { revert("Function not implemented"); } /** * @notice mintBatch function not needed */ function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public { revert("Function not implemented"); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165, ERC1155) returns (bool) { return super.supportsInterface(interfaceId); } //it will return the original NFT uri /** * @dev this method will return the NFT uri * @return Original NFT uri */ function uri(uint256 id) public view virtual override returns (string memory) { return ERC1155(originalNFT).uri(id); } function burn( address account, uint256 id, uint256 value ) public virtual { revert("Function not implemented"); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { revert("Function not implemented"); } /** * @dev only the splitter proxy associated to the NFT-TokenId can transfer tokens */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override { require( NFTSplitterAdmin(settings).isValidProxy(originalNFT, tokenId, address(this)) , "NFTSplitter: caller is not a valid proxy, owner nor approved " ); _safeTransferFrom(from, to, id, amount, data); } /** * @notice method used by the original NFT to initiate contract state * @dev it transfers the original nft to this contract and creates a new * nft than can be traded inside the app * @param _tokenId _tokenId original nft's tokenId * @param _price amount of tokens to transfer * @param _buyPercentage current token owner * @param _pieces amount of new tokens to mint */ function splitMyNFT( uint256 _tokenId, //TODO: remove this parameter uint256 _price, uint128 _buyPercentage, uint8 _pieces ) external onlyOriginalNFTOwner { require (unitPrice == 0, 'NFTSplitter: splitter already created' ); require(_price > 0, 'NFTSplitter: invalid price'); require(_pieces > 0, 'NFTSplitter: invalid pieces' ); require(_buyPercentage > 0, 'NFTSplitter: invalid percentage ' ); unitPrice = _price; tokenId = _tokenId; //TODO: remove this parameter, tokenId was instantiated in proxy creation pieces = _pieces; buyPercentage = _buyPercentage; originalOwner = msg.sender; //TODO: implement lock time logic //TODO: implement logic to not allow to sell more than initialSellSupply during lock time //lockEndDate = block.timestamp + (_lockTimeInDays * 1 days); //initialSellSupply = _initialSellAmount; _mint(msg.sender, tokenId, pieces, ""); //as name and symbol are not part of ERC1155 //contract needs to catch any error executing the functions //if there is any error the state of the variables does not change //meaning that state of the variables will not change in proxy contract try ERC1155(originalNFT).name() returns (string memory result) { name = string(abi.encodePacked("NFT Splitter - ", result)); } catch { emit Log("NFTSplitter: external call failed"); } try ERC1155(originalNFT).symbol() returns (string memory result) { symbol = string(abi.encodePacked("NS", result)); } catch { emit Log("NFTSplitter: external call failed"); } ERC1155(originalNFT).safeTransferFrom( msg.sender, address(this), tokenId, ERC1155(originalNFT).balanceOf(msg.sender, tokenId), "" ); emit NFTSplit(originalNFT, tokenId, pieces, unitPrice, buyPercentage); } /** * @dev method used by the original NFT to buy back any piece that was sold * @param _from current token owner * @param amount amount of tokens to transfer */ function buyBackPieces(address _from, uint256 amount) external payable onlyOriginalNFTOwner nonReentrant { //TODO: add support to interact with multiple users, currently this contracts only supports interactions between the original nft owner and one buyer uint buyBackPrice = (unitPrice + (unitPrice * buyPercentage / 100 )) * amount; require(msg.value >= buyBackPrice, 'NFTSplitter: insufficient value for this transaction'); _safeTransferFrom(_from, msg.sender, tokenId, amount, ""); (bool sent, ) = _from.call{value: buyBackPrice}(""); require(sent, "Failed to send Ether"); emit NFTSplitBuyBack(originalNFT, msg.sender, buyPercentage, buyBackPrice); } /** * @dev method used to buy a piece of the original NFT from the original Owner * * */ function buyPiecesFromOwner( uint256 amount) external payable notOriginalNFTOwner nonReentrant { //TODO: add support to interact with multiple users, currently this contracts only supports interactions between the original nft owner and one buyer uint currentSupply = balanceOf(originalOwner, tokenId); require(currentSupply >= amount, 'NFTSplitter: not enough pieces to buy'); require(originalOwner != msg.sender, 'NFTSplitter: you are the current nft owner'); uint piecePrice = unitPrice * amount; require(msg.value >= piecePrice, 'NFTSplitter: not enough value to buy pieces'); _safeTransferFrom(originalOwner, msg.sender, tokenId, amount, ""); (bool sent, ) = originalOwner.call{value: msg.value}(""); emit NFTSplitSold(originalOwner, msg.sender, amount, piecePrice); require(sent, "Failed to send Ether"); } /** * @dev this method will burn all the NFT pieces and it will transfer the original NFT to the new owner. * This method can only be executed if the address owns all the pieces. * */ function withdrawOriginalNFT() public ownsAllPieces nonReentrant { //burn pieces _burn(msg.sender, tokenId, pieces); ERC1155(originalNFT).safeTransferFrom( address(this), msg.sender, tokenId, ERC1155(originalNFT).balanceOf(address(this), tokenId), //sending all tokens that proxy owns, aridrops?? "" ); emit NFTWithdraw(originalNFT, msg.sender); } function onERC1155Received( address, /*_operator*/ address, /*_from*/ uint256 _id, uint256, /*_amount*/ bytes calldata /*_data*/ ) external override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, /*_operator*/ address, /*_from*/ uint256[] memory, /*_ids*/ uint256[] memory, /*_values*/ bytes memory /*_data*/ ) public pure override returns (bytes4) { return this.onERC1155BatchReceived.selector; } // Function to receive Ether. msg.data must be empty receive() external payable {} // Fallback function is called when msg.data is not empty fallback() external payable {} function getBalance() external view returns (uint256) { return address(this).balance; } /// @notice Withdraw any contract funds /// @dev Only the original NFT owner execute call this function function withdraw() public onlyOriginalNFTOwner{ //TODO: implement and create test for this scenario if applicable } }
it will return the original NFT uri* @dev this method will return the NFT uri @return Original NFT uri/
function uri(uint256 id) public view virtual override returns (string memory) { return ERC1155(originalNFT).uri(id); }
2,536,858
[ 1, 305, 903, 327, 326, 2282, 423, 4464, 2003, 225, 333, 707, 903, 327, 326, 423, 4464, 2003, 327, 19225, 423, 4464, 2003, 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 ]
[ 1, 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 ]
[ 1, 565, 445, 2003, 12, 11890, 5034, 612, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 327, 4232, 39, 2499, 2539, 12, 8830, 50, 4464, 2934, 1650, 12, 350, 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 ]
// SPDX-License-Identifier: MIT // pragma solidity >=0.4.21 <0.7.0; pragma solidity ^0.8.0; contract Ownable { // address of owner account address payable _owner; constructor () { // Initiliaztion of the _owner value with msg.sender _owner = payable(msg.sender); } modifier onlyOwner () { require(_owner == msg.sender, "You are not only the owner"); _; } function isOwner () public view returns (bool) { return (msg.sender == _owner); } }
address of owner account
contract Ownable { address payable _owner; pragma solidity ^0.8.0; constructor () { _owner = payable(msg.sender); } modifier onlyOwner () { require(_owner == msg.sender, "You are not only the owner"); _; } function isOwner () public view returns (bool) { return (msg.sender == _owner); } }
13,057,222
[ 1, 2867, 434, 3410, 2236, 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, 16351, 14223, 6914, 288, 203, 203, 225, 1758, 8843, 429, 389, 8443, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 225, 3885, 1832, 288, 203, 203, 565, 389, 8443, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1832, 288, 203, 565, 2583, 24899, 8443, 422, 1234, 18, 15330, 16, 315, 6225, 854, 486, 1338, 326, 3410, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 353, 5541, 1832, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 261, 3576, 18, 15330, 422, 389, 8443, 1769, 203, 225, 289, 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 ]
./full_match/69/0x8EB5A8B9732022F20ab4d3128DDf3a50a6dAa7A2/sources/contracts/OptionMarketPricer.sol
* @dev Calculates the impact a trade has on the base IV of the OptionBoard and the skew of the OptionListing. @param listing The OptionListing. @param trade The Trade. @param pricingGlobals The PricingGlobals. @param boardBaseIv The base IV of the OptionBoard./
function ivImpactForTrade( OptionMarket.OptionListing memory listing, OptionMarket.Trade memory trade, LyraGlobals.PricingGlobals memory pricingGlobals, uint boardBaseIv ) public pure returns (uint, uint) { uint orderSize = trade.amount.divideDecimal(pricingGlobals.standardSize); uint orderMoveBaseIv = orderSize / 100; uint orderMoveSkew = orderMoveBaseIv.multiplyDecimal(pricingGlobals.skewAdjustmentFactor); if (trade.isBuy) { return (boardBaseIv + orderMoveBaseIv, listing.skew + orderMoveSkew); return (boardBaseIv.sub(orderMoveBaseIv), listing.skew.sub(orderMoveSkew)); } }
13,238,135
[ 1, 10587, 326, 15800, 279, 18542, 711, 603, 326, 1026, 21602, 434, 326, 2698, 22233, 471, 326, 20001, 434, 326, 2698, 19081, 18, 225, 11591, 1021, 2698, 19081, 18, 225, 18542, 1021, 2197, 323, 18, 225, 31765, 19834, 1021, 453, 1512, 310, 19834, 18, 225, 11094, 2171, 45, 90, 1021, 1026, 21602, 434, 326, 2698, 22233, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 4674, 22683, 621, 1290, 22583, 12, 203, 565, 2698, 3882, 278, 18, 1895, 19081, 3778, 11591, 16, 203, 565, 2698, 3882, 278, 18, 22583, 3778, 18542, 16, 203, 565, 511, 93, 354, 19834, 18, 52, 1512, 310, 19834, 3778, 31765, 19834, 16, 203, 565, 2254, 11094, 2171, 45, 90, 203, 225, 262, 1071, 16618, 1135, 261, 11890, 16, 2254, 13, 288, 203, 565, 2254, 1353, 1225, 273, 18542, 18, 8949, 18, 2892, 831, 5749, 12, 683, 14774, 19834, 18, 10005, 1225, 1769, 203, 565, 2254, 1353, 7607, 2171, 45, 90, 273, 1353, 1225, 342, 2130, 31, 203, 565, 2254, 1353, 7607, 5925, 359, 273, 1353, 7607, 2171, 45, 90, 18, 7027, 1283, 5749, 12, 683, 14774, 19834, 18, 7771, 359, 19985, 6837, 1769, 203, 565, 309, 261, 20077, 18, 291, 38, 9835, 13, 288, 203, 1377, 327, 261, 3752, 2171, 45, 90, 397, 1353, 7607, 2171, 45, 90, 16, 11591, 18, 7771, 359, 397, 1353, 7607, 5925, 359, 1769, 203, 1377, 327, 261, 3752, 2171, 45, 90, 18, 1717, 12, 1019, 7607, 2171, 45, 90, 3631, 11591, 18, 7771, 359, 18, 1717, 12, 1019, 7607, 5925, 359, 10019, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-30 */ // File: @openzeppelin/[email protected]/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/[email protected]/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/OwnerAdminGuard.sol pragma solidity 0.8.12; contract OwnerAdminGuard is Ownable { address[2] private _admins; bool private _adminsSet; /// @notice Allows the owner to specify two addresses allowed to administer this contract /// @param admins A 2 item array of addresses function setAdmins(address[2] calldata admins) public { require(admins[0] != address(0) && admins[1] != address(0), "Invalid admin address"); _admins = admins; _adminsSet = true; } function _isOwnerOrAdmin(address addr) internal virtual view returns(bool){ return addr == owner() || ( _adminsSet && ( addr == _admins[0] || addr == _admins[1] ) ); } modifier onlyOwnerOrAdmin() { require(_isOwnerOrAdmin(msg.sender), "Not an owner or admin"); _; } } // File: contracts/AuthorizedCallerGuard.sol pragma solidity 0.8.12; contract AuthorizedCallerGuard is OwnerAdminGuard { /// @dev Keeps track of which contracts are explicitly allowed to interact with certain super contract functionality mapping(address => bool) public authorizedContracts; event AuthorizedContractAdded(address contractAddress, address addedBy); event AuthorizedContractRemoved(address contractAddress, address removedBy); /// @notice Allows the owner or an admin to authorize another contract to override token accruals on an individual token level /// @param contractAddress The authorized contract address function addAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin { require(_isContract(contractAddress), "Invalid contractAddress"); authorizedContracts[contractAddress] = true; emit AuthorizedContractAdded(contractAddress, _msgSender()); } /// @notice Allows the owner or an admin to remove an authorized contract /// @param contractAddress The contract address which should have its authorization revoked function removeAuthorizedContract(address contractAddress) public onlyOwnerOrAdmin { authorizedContracts[contractAddress] = false; emit AuthorizedContractRemoved(contractAddress, _msgSender()); } /// @dev Derived from @openzeppelin/contracts/utils/Address.sol function _isContract(address account) internal virtual view returns (bool) { if(account == address(0)) return false; // 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; } function _isAuthorizedContract(address addr) internal virtual view returns(bool){ return authorizedContracts[addr]; } modifier onlyAuthorizedCaller() { require(_isOwnerOrAdmin(_msgSender()) || _isAuthorizedContract(_msgSender()), "Sender is not authorized"); _; } modifier onlyAuthorizedContract() { require(_isAuthorizedContract(_msgSender()), "Sender is not authorized"); _; } } // File: @openzeppelin/[email protected]/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/[email protected]/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/[email protected]/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/[email protected]/token/ERC1155/IERC1155Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/[email protected]/token/ERC1155/IERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // File: contracts/IAwooMintableCollection.sol pragma solidity 0.8.12; interface IAwooMintableCollection is IERC1155 { struct TokenDetail { bool SoftLimit; bool Active; } struct TokenCount { uint256 TokenId; uint256 Count; } function supportsInterface(bytes4 interfaceId) external view returns (bool); function mint(address to, uint256 id, uint256 qty) external; function mintBatch(address to, uint256[] memory ids, uint256[] memory quantities) external; function burn(address from, uint256 id, uint256 qty) external; function tokensOfOwner(address owner) external view returns (TokenCount[] memory); function totalMinted(uint256 id) external view returns(uint256); function totalSupply(uint256 id) external view returns (uint256); function exists(uint256 id) external view returns (bool); function addToken(TokenDetail calldata tokenDetail, string memory tokenUri) external returns(uint256); function setTokenUri(uint256 id, string memory tokenUri) external; function setTokenActive(uint256 id, bool active) external; function setBaseUri(string memory baseUri) external; } // File: @openzeppelin/[email protected]/token/ERC1155/extensions/IERC1155MetadataURI.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: @openzeppelin/[email protected]/token/ERC1155/ERC1155.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin/[email protected]/token/ERC1155/extensions/ERC1155Supply.sol // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // File: @openzeppelin/[email protected]/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: contracts/AwooCollection.sol pragma solidity 0.8.12; contract AwooCollection is IAwooMintableCollection, ERC1155Supply, AuthorizedCallerGuard { using Strings for uint256; string public constant name = "Awoo Items"; string public constant symbol = "AWOOI"; uint16 public currentTokenId; bool public isActive; /// @notice Maps the tokenId of a specific mintable item to the details that define that item mapping(uint256 => TokenDetail) public tokenDetails; /// @notice Keeps track of the number of tokens that were burned to support "Soft" limits /// @dev Soft limits are the number of tokens available at any given time, so if 1 is burned, another can be minted mapping(uint256 => uint256) public tokenBurnCounts; /// @dev Allows us to have token-specific metadata uris that will override the baseUri mapping(uint256 => string) private _tokenUris; event TokenUriUpdated(uint256 indexed id, string newUri, address updatedBy); constructor(address awooStoreAddress, string memory baseUri) ERC1155(baseUri){ // Allow the Awoo Store contract to interact with this contract to faciliate minting and burning addAuthorizedContract(awooStoreAddress); } /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IAwooMintableCollection) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IAwooMintableCollection).interfaceId || interfaceId == type(IERC1155).interfaceId || interfaceId == ERC1155Supply.totalSupply.selector || interfaceId == ERC1155Supply.exists.selector; } /// @notice Allows authorized contracts to mints tokens to the specified recipient /// @param to The recipient address /// @param id The Id of the specific token to mint /// @param qty The number of specified tokens that should be minted function mint(address to, uint256 id, uint256 qty ) external whenActive onlyAuthorizedContract { _mint(to, id, qty, ""); } /// @notice Allows authorized contracts to mint multiple different tokens to the specified recipient /// @param to The recipient address /// @param ids The Ids of the specific tokens to mint /// @param quantities The number of each of the specified tokens that should be minted function mintBatch(address to, uint256[] memory ids, uint256[] memory quantities ) external whenActive onlyAuthorizedContract { _mintBatch(to, ids, quantities, ""); } /// @notice Burns the specified number of tokens. /// @notice Only the holder or an approved operator is authorized to burn /// @notice Operator approvals must have been explicitly allowed by the token holder /// @param from The account from which the specified tokens will be burned /// @param id The Id of the tokens that will be burned /// @param qty The number of specified tokens that will be burned function burn(address from, uint256 id, uint256 qty) external { require(exists(id), "Query for non-existent id"); require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "Not owner or approved"); _burn(from, id, qty); } /// @notice Burns the specified number of each of the specified tokens. /// @notice Only the holder or an approved operator is authorized to burn /// @notice Operator approvals must have been explicitly allowed by the token holder /// @param from The account from which the specified tokens will be burned /// @param ids The Ids of the tokens that will be burned /// @param quantities The number of each of the specified tokens that will be burned function burnBatch(address from, uint256[] memory ids, uint256[] memory quantities) external { require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "Not owner or approved"); for(uint256 i; i < ids.length; i++){ require(exists(ids[i]), "Query for non-existent id"); } _burnBatch(from, ids, quantities); } /// @notice Returns the metadata uri for the specified token /// @dev By default, token-specific uris are given preference /// @param id The id of the token for which the uri should be returned /// @return A uri string function uri(uint256 id) public view override returns (string memory) { require(exists(id), "Query for non-existent id"); return bytes(_tokenUris[id]).length > 0 ? _tokenUris[id] : string.concat(ERC1155.uri(id), id.toString(), ".json"); } /// @notice Returns the number of each token held by the specified owner address /// @param owner The address of the token owner/holder /// @return An array of Tuple(uint256,uint256) indicating the number of tokens held function tokensOfOwner(address owner) external view returns (TokenCount[] memory) { TokenCount[] memory ownerTokenCounts = new TokenCount[](currentTokenId); for(uint256 i = 1; i <= currentTokenId; i++){ uint256 count = balanceOf(owner, i); ownerTokenCounts[i-1] = TokenCount(i, count); } return ownerTokenCounts; } /// @notice Returns the total number of tokens minted for the specified token id /// @dev For tokens that have a soft limit, the number of burned tokens is included /// so the result is based on the total number of tokens minted, regardless of whether /// or not they were subsequently burned /// @param id The id of the token to query /// @return A uint256 value indicating the total number of tokens minted and burned for the specified token id function totalMinted(uint256 id) isValidTokenId(id) external view returns(uint256) { TokenDetail memory tokenDetail = tokenDetails[id]; if(tokenDetail.SoftLimit){ return ERC1155Supply.totalSupply(id); } else { return (ERC1155Supply.totalSupply(id) + tokenBurnCounts[id]); } } /// @notice Returns the current number of tokens that were minted and not burned /// @param id The id of the token to query /// @return A uint256 value indicating the number of tokens which have not been burned function totalSupply(uint256 id) public view virtual override(ERC1155Supply,IAwooMintableCollection) returns (uint256) { return ERC1155Supply.totalSupply(id); } /// @notice Determines whether or not the specified token id is valid and at least 1 has been minted /// @param id The id of the token to validate /// @return A boolean value indicating the existence of the specified token id function exists(uint256 id) public view virtual override(ERC1155Supply,IAwooMintableCollection) returns (bool) { return ERC1155Supply.exists(id); } /// @notice Allows authorized individuals or contracts to add new tokens that can be minted /// @param tokenDetail An object describing the token being added /// @param tokenUri The specific uri to use for the token being added /// @return A uint256 value representing the id of the token function addToken(TokenDetail calldata tokenDetail, string memory tokenUri) external isAuthorized returns(uint256){ currentTokenId++; if(bytes(tokenUri).length > 0) { _tokenUris[currentTokenId] = tokenUri; } tokenDetails[currentTokenId] = tokenDetail; return currentTokenId; } /// @notice Allows authorized individuals or contracts to set the base metadata uri /// @dev It is assumed that the baseUri value will end with / /// @param baseUri The uri to use as the base for all tokens that don't have a token-specific uri function setBaseUri(string memory baseUri) external isAuthorized { _setURI(baseUri); } /// @notice Allows authorized individuals or contracts to set the base metadata uri on a per token level /// @param id The id of the token /// @param tokenUri The uri to use for the specified token id function setTokenUri(uint256 id, string memory tokenUri) external isAuthorized isValidTokenId(id) { _tokenUris[id] = tokenUri; emit TokenUriUpdated(id, tokenUri, _msgSender()); } /// @notice Allows authorized individuals or contracts to activate/deactivate minting of the specified token id /// @param id The id of the token /// @param active A boolean value indicating whether or not minting is allowed for this token function setTokenActive(uint256 id, bool active) external isAuthorized isValidTokenId(id) { tokenDetails[id].Active = active; } /// @notice Allows authorized individuals to activate/deactivate minting of all tokens /// @param active A boolean value indicating whether or not minting is allowed function setActive(bool active) external onlyOwnerOrAdmin { isActive = active; } function rescueEth() external onlyOwner { require(payable(owner()).send(address(this).balance)); } /// @dev Hook to allows us to count the burned tokens even if they're just transferred to the zero address function _beforeTokenTransfer(address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { tokenBurnCounts[ids[i]] += amounts[i]; } } } modifier whenActive(){ require(isActive, "Minting inactive"); _; } modifier isValidTokenId(uint256 id) { require(id <= currentTokenId, "Invalid tokenId"); _; } modifier isValidTokenIds(uint256[] memory ids){ for(uint256 i = 0; i < ids.length; i++){ require(ids[i] <= currentTokenId, "Invalid tokenId"); } _; } modifier isAuthorized() { require(_isAuthorizedContract(_msgSender()) || _isOwnerOrAdmin(_msgSender()), "Unauthorized"); _; } }
@notice Returns the number of each token held by the specified owner address @param owner The address of the token owner/holder @return An array of Tuple(uint256,uint256) indicating the number of tokens held
function tokensOfOwner(address owner) external view returns (TokenCount[] memory) { TokenCount[] memory ownerTokenCounts = new TokenCount[](currentTokenId); for(uint256 i = 1; i <= currentTokenId; i++){ uint256 count = balanceOf(owner, i); ownerTokenCounts[i-1] = TokenCount(i, count); } return ownerTokenCounts; }
2,015,114
[ 1, 1356, 326, 1300, 434, 1517, 1147, 15770, 635, 326, 1269, 3410, 1758, 225, 3410, 1021, 1758, 434, 326, 1147, 3410, 19, 4505, 327, 1922, 526, 434, 7257, 12, 11890, 5034, 16, 11890, 5034, 13, 11193, 326, 1300, 434, 2430, 15770, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2430, 951, 5541, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 1345, 1380, 8526, 3778, 13, 288, 203, 3639, 3155, 1380, 8526, 3778, 3410, 1345, 9211, 273, 394, 3155, 1380, 8526, 12, 2972, 1345, 548, 1769, 203, 540, 203, 3639, 364, 12, 11890, 5034, 277, 273, 404, 31, 277, 1648, 23719, 548, 31, 277, 27245, 95, 203, 5411, 2254, 5034, 1056, 273, 11013, 951, 12, 8443, 16, 277, 1769, 203, 5411, 3410, 1345, 9211, 63, 77, 17, 21, 65, 273, 3155, 1380, 12, 77, 16, 1056, 1769, 203, 3639, 289, 203, 3639, 327, 3410, 1345, 9211, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../erc20/ERC20.sol"; import "../utils/SafeMath.sol"; import "../utils/Ownable.sol"; import "../utils/ReentrancyGuard.sol"; import "./GothTokenV2.sol"; contract GothStake is ERC20("GOTH Bits", "bGOTH"), Ownable, ReentrancyGuard { using SafeMath for uint256; GothTokenV2 public goth; uint256 public enterFeeMod; // (amount * 1e18) / enterFeeMod = Actual Fee uint256 public leaveFee; // Static uint256 public mintRate; // 0-15 uint256 public treasuryPercent; // Default - 100 address public treasuryAddress; uint256 public teamPercent; // Default - 100 address public teamAddress; address public feeAddress; mapping(address => uint256) public lastClaimTime; uint256 public totalStaked; event ChangeGothOwner (address newOwner); event SetEnterFeeMod (uint256 newFeeMod); event SetLeaveFee (uint256 newLeavefee); event SetMintRate (uint256 newMintRate); event SetTreasuryAddress (address newAddress); event SetTeamAddress (address newAddress); event SetFeeAddress (address feeAddress); event Enter (address indexed account, uint256 share); event Leave (address indexed account, uint256 share); event Gather (address indexed account, uint256 amount); constructor (GothTokenV2 _goth) { goth = _goth; enterFeeMod = 2.5e8; leaveFee = 1.5e16; mintRate = 10; treasuryPercent = 100; teamPercent = 100; treasuryAddress = 0xDCb9C36998703ae5CEE2ec07Bef76e61A571906D; teamAddress = 0x8A1eA60Fe793FE009078A74d6167a8EeaD25f7F1; feeAddress = 0xbD2171Ea845D383e731ab29eDbCDd6f121305be3; } function changeGothOwner (address newOwner) public onlyOwner { require(newOwner != address(0) || newOwner != address(1), "changeGothOwner: cannot be zero addresses"); goth.transferOwnership(newOwner); emit ChangeGothOwner(newOwner); } function setEnterFeeMod (uint256 newFeeMod) public onlyOwner { require(newFeeMod <= 1e13 && newFeeMod >= 1e8, "setEnterFeeMod: enter fee mod too high"); enterFeeMod = newFeeMod; emit SetEnterFeeMod(newFeeMod); } function setLeaveFee (uint256 newLeaveFee) public onlyOwner { require(newLeaveFee <= 1e17, "setLeaveFee: leave fee too high"); leaveFee = newLeaveFee; emit SetLeaveFee(newLeaveFee); } function setTreasuryAddress (address newTreasury) public onlyOwner { require(newTreasury != address(0) || newTreasury != address(1), "setTreasuryAddress: cannot be zero addresses"); treasuryAddress = newTreasury; emit SetTreasuryAddress(newTreasury); } function setTeamAddress (address newTeam) public onlyOwner { require(newTeam != address(0) || newTeam != address(1), "setTeamAddress: cannot be zero addresses"); teamAddress = newTeam; emit SetTreasuryAddress(newTeam); } function setFeeAddress (address newFeeAddress) public onlyOwner { require(newFeeAddress != address(0) || newFeeAddress != address(1), "setFeeAddress: cannot be zero addresses"); feeAddress = newFeeAddress; emit SetFeeAddress(newFeeAddress); } function setMintRate (uint256 newMintRate) public onlyOwner { require(newMintRate <= 15, "setMintRate: mint rate too high"); mintRate = newMintRate; emit SetMintRate(newMintRate); } function mintReward (address account, uint256 share) internal { // Calculate the time that has passed between the users last claim and the current block. uint256 timeElapsed = block.timestamp.sub(lastClaimTime[account]); // Get the percentage of GOTH to be minted to stakers uint256 allocation = 1000 - treasuryPercent - teamPercent; // We calculate total mint amounts for the pool, team and treasury, mint rate is not in wei // format, so we multiply it by 1e18 which moves the decimals 18 places to the required number // respresented in wei, this also provides precision. Additionally, since team and treasury // are not further divided we multiply it by the time elapsed to get the correct mint amount // for those allocations. uint256 poolShare = mintRate.mul(allocation).div(1000); uint256 teamShare = mintRate.mul(1e18).mul(teamPercent).div(1000).mul(timeElapsed); uint256 treasuryShare = mintRate.mul(1e18).mul(treasuryPercent).div(1000).mul(timeElapsed); // Here, we calculate the stakers(user) share of the pool using the previously calculated pool allocation. // We multiplty the user share by 1e36, to ensure token precision, then we divide it by the total amount // of GOTH within the pool and multiply it further by 100 to find the stakers share, as percentage // of the pool. uint256 stakerShare = share.mul(1e36).div(totalStaked).mul(100); // We calculate the reward amount by multiplying the pool share by the stakers share, then divide it by 100 // and then 1e18, we could represent both of those divisions within one number, but this is clearer to see // that the 100 is a process of finding a percentage and then the 1e18 is the process of bringing the number back // down to the correct value after multiplying for token precision, this is then multiplied by the time elapsed // since last claim. uint256 reward = poolShare.mul(stakerShare).div(100).div(1e18).mul(timeElapsed); // Each of the share amounts are minted, with the user amount being sent to their address, and the team // and treasury respectively. goth.mint(account, reward); goth.mint(teamAddress, teamShare); goth.mint(treasuryAddress, treasuryShare); // The users last claim time is updated with the current block timestamp. lastClaimTime[account] = block.timestamp; } function enter(uint256 amount) public nonReentrant payable { require(msg.value >= amount.div(enterFeeMod), "enter: supplied fee too little"); require(goth.balanceOf(msg.sender) >= amount, "enter: not enough GOTH"); // Check to see if the sender has GOTH staked already and if they do it will // gather the accrued rewards up until this point, this is to prevent a user from // entering the pool to boost their share for the sole purpose of gathering the reward // then withdrawing again. if (balanceOf(msg.sender) > 0) { mintReward(msg.sender, balanceOf(msg.sender)); } // bGOTH is minted 1:1 to entered GOTH _mint(msg.sender, amount); goth.transferFrom(msg.sender, address(this), amount); totalStaked = totalStaked.add(amount); // Users last claim time set to the current block timestamp lastClaimTime[msg.sender] = block.timestamp; emit Enter(msg.sender, amount); } function leave(uint256 share) public nonReentrant payable { require(msg.value >= leaveFee, "leave: supplied fee too little"); require(balanceOf(msg.sender) >= share, "leave: not enough bGOTH"); // We can remove part of, or all of the share. This is also taken into consideration // when minting the users reward based on how much they are removing from the pool. if (share == 0) { mintReward(msg.sender, balanceOf(msg.sender)); } else { mintReward(msg.sender, balanceOf(msg.sender)); _burn(msg.sender, share); goth.transfer(msg.sender, share); // We update total staked in the pool here, we do this because the balance of the account // might be different from the total actually entered by stakers, this would mess with the // rewards in a negative way. totalStaked = totalStaked.sub(share); emit Leave(msg.sender, share); } } // This calculates a users pending rewards without costing gas, it uses the same logic as the // mint reward function, but does not change the state of the contract. function accruedReward (address account) external view returns (uint256) { uint256 timeElapsed = block.timestamp.sub(lastClaimTime[account]); uint256 allocation = 1000 - treasuryPercent - teamPercent; uint256 poolShare = mintRate.mul(allocation).div(1000); uint256 stakerShare = balanceOf(account).mul(1e36).div(totalStaked).mul(100); uint256 reward = poolShare.mul(stakerShare).div(100).div(1e18).mul(timeElapsed); return reward; } // this function can only be called by the owner, and will withdraw all the avax at this contract // address and send it to the address defined by the feeAddress property within this contract. function withdrawFees () external onlyOwner { (bool sent, bytes memory data) = feeAddress.call{value: address(this).balance}(""); require(sent, "withdrawFees: withdraw failed"); } receive() external payable {} fallback() external payable {} }
We can remove part of, or all of the share. This is also taken into consideration when minting the users reward based on how much they are removing from the pool. We update total staked in the pool here, we do this because the balance of the account might be different from the total actually entered by stakers, this would mess with the rewards in a negative way.
function leave(uint256 share) public nonReentrant payable { require(msg.value >= leaveFee, "leave: supplied fee too little"); require(balanceOf(msg.sender) >= share, "leave: not enough bGOTH"); if (share == 0) { mintReward(msg.sender, balanceOf(msg.sender)); } else { mintReward(msg.sender, balanceOf(msg.sender)); _burn(msg.sender, share); goth.transfer(msg.sender, share); totalStaked = totalStaked.sub(share); emit Leave(msg.sender, share); } }
12,656,076
[ 1, 3218, 848, 1206, 1087, 434, 16, 578, 777, 434, 326, 7433, 18, 1220, 353, 2546, 9830, 1368, 5260, 367, 1347, 312, 474, 310, 326, 3677, 19890, 2511, 603, 3661, 9816, 2898, 854, 9427, 628, 326, 2845, 18, 1660, 1089, 2078, 384, 9477, 316, 326, 2845, 2674, 16, 732, 741, 333, 2724, 326, 11013, 434, 326, 2236, 4825, 506, 3775, 628, 326, 2078, 6013, 16219, 635, 384, 581, 414, 16, 333, 4102, 12755, 598, 326, 283, 6397, 316, 279, 6092, 4031, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 8851, 12, 11890, 5034, 7433, 13, 1071, 1661, 426, 8230, 970, 8843, 429, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 8851, 14667, 16, 315, 19574, 30, 4580, 14036, 4885, 12720, 8863, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 7433, 16, 315, 19574, 30, 486, 7304, 324, 43, 18307, 8863, 203, 203, 3639, 309, 261, 14419, 422, 374, 13, 203, 3639, 288, 203, 5411, 312, 474, 17631, 1060, 12, 3576, 18, 15330, 16, 11013, 951, 12, 3576, 18, 15330, 10019, 203, 3639, 289, 203, 3639, 469, 203, 3639, 288, 203, 5411, 312, 474, 17631, 1060, 12, 3576, 18, 15330, 16, 11013, 951, 12, 3576, 18, 15330, 10019, 203, 203, 5411, 389, 70, 321, 12, 3576, 18, 15330, 16, 7433, 1769, 203, 5411, 2363, 76, 18, 13866, 12, 3576, 18, 15330, 16, 7433, 1769, 203, 203, 5411, 2078, 510, 9477, 273, 2078, 510, 9477, 18, 1717, 12, 14419, 1769, 203, 203, 5411, 3626, 21131, 12, 3576, 18, 15330, 16, 7433, 1769, 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 ]
./full_match/44787/0xa8eD3E16015582Ae64fF1d7fF656096fc5553a55/sources/contracts/NFTMagicPunkFull.sol
* @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`./
contract NFTMagicPunkFull is ERC721, Ownable, Pausable { using SafeMath for uint256; using Counters for Counters.Counter; string private _nftBaseURI = ""; uint256 private _nftItemPrice = 10000000000000000000; uint256 private _nftMintAtOnce = 50; bool public saleIsActive = true; uint256 public constant nftMaxSupply = 10000; mapping(uint256 => uint256) private _totalSupply; Counters.Counter private _tokenIdCounter; constructor() ERC721("NFTMagicPunkNew", "NFTP") function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity ^0.8.0; } pragma solidity ^0.8.0; { } function mineReserves(uint _amount) public onlyOwner { for(uint x = 0; x < _amount; x++){ mint_main(); } } function mineReserves(uint _amount) public onlyOwner { for(uint x = 0; x < _amount; x++){ mint_main(); } } function setSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function _baseURI() internal view override returns (string memory) { return _nftBaseURI; } function setBaseURI (string memory _uri) public onlyOwner { _nftBaseURI = _uri; } function mintOne() public payable { require(saleIsActive, "Sale must be active to mint"); require(msg.value >= getItemPrice(), "Insufficient Token or Token value sent is not correct"); require(_tokenIdCounter.current() <= nftMaxSupply, "Purchase would exceed max supply"); mint_main(); } function mintMulti(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens > 0 && numberOfTokens <= _nftMintAtOnce, "To many NFT's at once"); require(msg.value >= getItemPrice().mul(numberOfTokens), "Insufficient Token or Token value sent is not correct"); require(_tokenIdCounter.current().add(numberOfTokens) <= nftMaxSupply, "Purchase would exceed max supply"); for (uint256 i = 0; i < numberOfTokens; i++) { mint_main(); } } function mintMulti(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens > 0 && numberOfTokens <= _nftMintAtOnce, "To many NFT's at once"); require(msg.value >= getItemPrice().mul(numberOfTokens), "Insufficient Token or Token value sent is not correct"); require(_tokenIdCounter.current().add(numberOfTokens) <= nftMaxSupply, "Purchase would exceed max supply"); for (uint256 i = 0; i < numberOfTokens; i++) { mint_main(); } } function mint_main() private { _safeMint(msg.sender, _tokenIdCounter.current() + 1); _tokenIdCounter.increment(); } function totalSupply() public view virtual returns (uint256) { return _tokenIdCounter.current(); } function getTotalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } function exists(uint256 id) public view virtual returns (bool) { return getTotalSupply(id) > 0; } function mintTokenId(address to, uint256 id) public onlyOwner { require(_totalSupply[id] == 0, "this NFT is already owned by someone"); _tokenIdCounter.increment(); _mint(to, id); } function safeMint(address to) public onlyOwner { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); } function getItemPrice() public view returns (uint256) { return _nftItemPrice; } function setItemPrice(uint256 price) public onlyOwner { _nftItemPrice = price; } function getMintAtOnce() public view returns (uint256) { return _nftMintAtOnce; } function setMintAtOnce(uint256 _items) public onlyOwner { _nftMintAtOnce = _items; } function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } }
13,246,409
[ 1, 2888, 4009, 502, 392, 288, 45, 654, 39, 27, 5340, 97, 1375, 2316, 548, 68, 1147, 353, 906, 4193, 358, 333, 6835, 3970, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 97, 635, 1375, 9497, 68, 628, 1375, 2080, 9191, 333, 445, 353, 2566, 18, 2597, 1297, 327, 2097, 348, 7953, 560, 3451, 358, 6932, 326, 1147, 7412, 18, 971, 1281, 1308, 460, 353, 2106, 578, 326, 1560, 353, 486, 8249, 635, 326, 8027, 16, 326, 7412, 903, 506, 15226, 329, 18, 1021, 3451, 848, 506, 12700, 316, 348, 7953, 560, 598, 1375, 45, 654, 39, 27, 5340, 18, 265, 654, 39, 27, 5340, 8872, 18, 9663, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 423, 4464, 19289, 52, 1683, 5080, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 16, 21800, 16665, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 377, 203, 565, 533, 3238, 389, 82, 1222, 2171, 3098, 273, 1408, 31, 203, 202, 203, 565, 2254, 5034, 3238, 389, 82, 1222, 1180, 5147, 273, 2130, 12648, 2787, 11706, 31, 203, 202, 203, 565, 2254, 5034, 3238, 389, 82, 1222, 49, 474, 861, 12212, 273, 6437, 31, 203, 377, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 638, 31, 203, 377, 203, 565, 2254, 5034, 1071, 5381, 290, 1222, 2747, 3088, 1283, 273, 12619, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 4963, 3088, 1283, 31, 203, 202, 203, 565, 9354, 87, 18, 4789, 3238, 389, 2316, 548, 4789, 31, 203, 203, 203, 565, 3885, 1435, 203, 3639, 4232, 39, 27, 5340, 2932, 50, 4464, 19289, 52, 1683, 1908, 3113, 315, 50, 17104, 7923, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 288, 203, 202, 203, 565, 289, 203, 203, 565, 445, 312, 558, 607, 264, 3324, 12, 11890, 389, 8949, 13, 2 ]
./partial_match/1/0xB985eA1be961f7c4A4C45504444C02c88c4fdEF9/sources/lib/hats-module/src/HatsModuleFactory.sol
import { console2 } from "forge-std/Test.sol"; remove before deploy
import { HatsModule } from "./HatsModule.sol";
2,750,327
[ 1, 5666, 288, 2983, 22, 289, 628, 315, 1884, 908, 17, 5084, 19, 4709, 18, 18281, 14432, 225, 1206, 1865, 7286, 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, 5666, 288, 670, 2323, 3120, 289, 628, 25165, 44, 2323, 3120, 18, 18281, 14432, 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 ]
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "./WeightedStaking.sol"; import "./IStaking.sol"; import "../../rsk/RSKAddrValidator.sol"; import "../Vesting/ITeamVesting.sol"; import "../ApprovalReceiver.sol"; /** * @title Staking contract. * @notice Pay-in and pay-out function for staking and withdrawing tokens. * Staking is delegated and vested: To gain voting power, SOV holders must * stake their SOV for a given period of time. Aside from Bitocracy * participation, there's a financially-rewarding reason for staking SOV. * Tokenholders who stake their SOV receive staking rewards, a pro-rata share * of the revenue that the platform generates from various transaction fees * plus revenues from stakers who have a portion of their SOV slashed for * early unstaking. * */ contract Staking is IStaking, WeightedStaking, ApprovalReceiver { /** * @notice Stake the given amount for the given duration of time. * @param amount The number of tokens to stake. * @param until Timestamp indicating the date until which to stake. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stake( uint96 amount, uint256 until, address stakeFor, address delegatee ) external { _stake(msg.sender, amount, until, stakeFor, delegatee, false); } /** * @notice Stake the given amount for the given duration of time. * @dev This function will be invoked from receiveApproval * @dev SOV.approveAndCall -> this.receiveApproval -> this.stakeWithApproval * @param sender The sender of SOV.approveAndCall * @param amount The number of tokens to stake. * @param until Timestamp indicating the date until which to stake. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stakeWithApproval( address sender, uint96 amount, uint256 until, address stakeFor, address delegatee ) public onlyThisContract { _stake(sender, amount, until, stakeFor, delegatee, false); } /** * @notice Send sender's tokens to this contract and update its staked balance. * @param sender The sender of the tokens. * @param amount The number of tokens to send. * @param until The date until which the tokens will be staked. * @param stakeFor The beneficiary whose stake will be increased. * @param delegatee The address of the delegatee or stakeFor if default 0x0. * @param timeAdjusted Whether fixing date to stacking periods or not. * */ function _stake( address sender, uint96 amount, uint256 until, address stakeFor, address delegatee, bool timeAdjusted ) internal { require(amount > 0, "Staking::stake: amount of tokens to stake needs to be bigger than 0"); if (!timeAdjusted) { until = timestampToLockDate(until); } require(until > block.timestamp, "Staking::timestampToLockDate: staking period too short"); /// @dev Stake for the sender if not specified otherwise. if (stakeFor == address(0)) { stakeFor = sender; } /// @dev Delegate for stakeFor if not specified otherwise. if (delegatee == address(0)) { delegatee = stakeFor; } /// @dev Do not stake longer than the max duration. if (!timeAdjusted) { uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); if (until > latest) until = latest; } uint96 previousBalance = currentBalance(stakeFor, until); /// @dev Increase stake. _increaseStake(sender, amount, stakeFor, until); if (previousBalance == 0) { /// @dev Regular delegation if it's a first stake. _delegate(stakeFor, delegatee, until); } else { address previousDelegatee = delegates[stakeFor][until]; if (previousDelegatee != delegatee) { /// @dev Update delegatee. delegates[stakeFor][until] = delegatee; /// @dev Decrease stake on previous balance for previous delegatee. _decreaseDelegateStake(previousDelegatee, until, previousBalance); /// @dev Add previousBalance to amount. amount = add96(previousBalance, amount, "Staking::stake: balance overflow"); } /// @dev Increase stake. _increaseDelegateStake(delegatee, until, amount); } } /** * @notice Extend the staking duration until the specified date. * @param previousLock The old unlocking timestamp. * @param until The new unlocking timestamp in seconds. * */ function extendStakingDuration(uint256 previousLock, uint256 until) public { until = timestampToLockDate(until); require(previousLock <= until, "Staking::extendStakingDuration: cannot reduce the staking duration"); /// @dev Do not exceed the max duration, no overflow possible. uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); if (until > latest) until = latest; /// @dev Update checkpoints. /// @dev TODO James: Can reading stake at block.number -1 cause trouble with multiple tx in a block? uint96 amount = getPriorUserStakeByDate(msg.sender, previousLock, block.number - 1); require(amount > 0, "Staking::extendStakingDuration: nothing staked until the previous lock date"); _decreaseUserStake(msg.sender, previousLock, amount); _increaseUserStake(msg.sender, until, amount); _decreaseDailyStake(previousLock, amount); _increaseDailyStake(until, amount); /// @dev Delegate might change: if there is already a delegate set for the until date, it will remain the delegate for this position address delegateFrom = delegates[msg.sender][previousLock]; address delegateTo = delegates[msg.sender][until]; if (delegateTo == address(0)) { delegateTo = delegateFrom; delegates[msg.sender][until] = delegateFrom; } delegates[msg.sender][previousLock] = address(0); _decreaseDelegateStake(delegateFrom, previousLock, amount); _increaseDelegateStake(delegateTo, until, amount); emit ExtendedStakingDuration(msg.sender, previousLock, until); } /** * @notice Send sender's tokens to this contract and update its staked balance. * @param sender The sender of the tokens. * @param amount The number of tokens to send. * @param stakeFor The beneficiary whose stake will be increased. * @param until The date until which the tokens will be staked. * */ function _increaseStake( address sender, uint96 amount, address stakeFor, uint256 until ) internal { /// @dev Retrieve the SOV tokens. bool success = SOVToken.transferFrom(sender, address(this), amount); require(success); /// @dev Increase staked balance. uint96 balance = currentBalance(stakeFor, until); balance = add96(balance, amount, "Staking::increaseStake: balance overflow"); /// @dev Update checkpoints. _increaseDailyStake(until, amount); _increaseUserStake(stakeFor, until, amount); emit TokensStaked(stakeFor, amount, until, balance); } /** * @notice Stake tokens according to the vesting schedule. * @param amount The amount of tokens to stake. * @param cliff The time interval to the first withdraw. * @param duration The staking duration. * @param intervalLength The length of each staking interval when cliff passed. * @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. * @param delegatee The address of the delegatee or 0x0 if there is none. * */ function stakesBySchedule( uint256 amount, uint256 cliff, uint256 duration, uint256 intervalLength, address stakeFor, address delegatee ) public { /** * @dev Stake them until lock dates according to the vesting schedule. * Note: because staking is only possible in periods of 2 weeks, * the total duration might end up a bit shorter than specified * depending on the date of staking. * */ uint256 start = timestampToLockDate(block.timestamp + cliff); if (duration > MAX_DURATION) { duration = MAX_DURATION; } uint256 end = timestampToLockDate(block.timestamp + duration); uint256 numIntervals = (end - start) / intervalLength + 1; uint256 stakedPerInterval = amount / numIntervals; /// @dev stakedPerInterval might lose some dust on rounding. Add it to the first staking date. if (numIntervals >= 1) { _stake(msg.sender, uint96(amount - stakedPerInterval * (numIntervals - 1)), start, stakeFor, delegatee, true); } /// @dev Stake the rest in 4 week intervals. for (uint256 i = start + intervalLength; i <= end; i += intervalLength) { /// @dev Stakes for itself, delegates to the owner. _stake(msg.sender, uint96(stakedPerInterval), i, stakeFor, delegatee, true); } } /** * @notice Withdraw the given amount of tokens if they are unlocked. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * */ function withdraw( uint96 amount, uint256 until, address receiver ) public { _withdraw(amount, until, receiver, false); } /** * @notice Withdraw the given amount of tokens. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting * */ function governanceWithdraw( uint96 amount, uint256 until, address receiver ) public { require(vestingWhitelist[msg.sender], "unauthorized"); _withdraw(amount, until, receiver, true); } /** * @notice Withdraw tokens for vesting contract. * @param vesting The address of Vesting contract. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @dev Can be invoked only by whitelisted contract passed to governanceWithdrawVesting. * */ function governanceWithdrawVesting(address vesting, address receiver) public onlyOwner { vestingWhitelist[vesting] = true; ITeamVesting(vesting).governanceWithdrawTokens(receiver); vestingWhitelist[vesting] = false; emit VestingTokensWithdrawn(vesting, receiver); } /** * @notice Send user' staked tokens to a receiver taking into account punishments. * Sovryn encourages long-term commitment and thinking. When/if you unstake before * the end of the staking period, a percentage of the original staking amount will * be slashed. This amount is also added to the reward pool and is distributed * between all other stakers. * * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * @param receiver The receiver of the tokens. If not specified, send to the msg.sender * @param isGovernance Whether all tokens (true) * or just unlocked tokens (false). * */ function _withdraw( uint96 amount, uint256 until, address receiver, bool isGovernance ) internal { until = _adjustDateForOrigin(until); _validateWithdrawParams(amount, until); /// @dev Determine the receiver. if (receiver == address(0)) receiver = msg.sender; /// @dev Update the checkpoints. _decreaseDailyStake(until, amount); _decreaseUserStake(msg.sender, until, amount); _decreaseDelegateStake(delegates[msg.sender][until], until, amount); /// @dev Early unstaking should be punished. if (block.timestamp < until && !allUnlocked && !isGovernance) { uint96 punishedAmount = _getPunishedAmount(amount, until); amount -= punishedAmount; /// @dev punishedAmount can be 0 if block.timestamp are very close to 'until' if (punishedAmount > 0) { require(address(feeSharing) != address(0), "Staking::withdraw: FeeSharing address wasn't set"); /// @dev Move punished amount to fee sharing. /// @dev Approve transfer here and let feeSharing do transfer and write checkpoint. SOVToken.approve(address(feeSharing), punishedAmount); feeSharing.transferTokens(address(SOVToken), punishedAmount); } } /// @dev transferFrom bool success = SOVToken.transfer(receiver, amount); require(success, "Staking::withdraw: Token transfer failed"); emit TokensWithdrawn(msg.sender, receiver, amount); } /** * @notice Get available and punished amount for withdrawing. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function getWithdrawAmounts(uint96 amount, uint256 until) public view returns (uint96, uint96) { _validateWithdrawParams(amount, until); uint96 punishedAmount = _getPunishedAmount(amount, until); return (amount - punishedAmount, punishedAmount); } /** * @notice Get punished amount for withdrawing. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function _getPunishedAmount(uint96 amount, uint256 until) internal view returns (uint96) { uint256 date = timestampToLockDate(block.timestamp); uint96 weight = computeWeightByDate(until, date); /// @dev (10 - 1) * WEIGHT_FACTOR weight = weight * weightScaling; return (amount * weight) / WEIGHT_FACTOR / 100; } /** * @notice Validate withdraw parameters. * @param amount The number of tokens to withdraw. * @param until The date until which the tokens were staked. * */ function _validateWithdrawParams(uint96 amount, uint256 until) internal view { require(amount > 0, "Staking::withdraw: amount of tokens to be withdrawn needs to be bigger than 0"); uint96 balance = getPriorUserStakeByDate(msg.sender, until, block.number - 1); require(amount <= balance, "Staking::withdraw: not enough balance"); } /** * @notice Get the current balance of an account locked until a certain date. * @param account The user address. * @param lockDate The lock date. * @return The stake amount. * */ function currentBalance(address account, uint256 lockDate) internal view returns (uint96) { return userStakingCheckpoints[account][lockDate][numUserStakingCheckpoints[account][lockDate] - 1].stake; } /** * @notice Get the number of staked tokens held by the user account. * @dev Iterate checkpoints adding up stakes. * @param account The address of the account to get the balance of. * @return The number of tokens held. * */ function balanceOf(address account) public view returns (uint96 balance) { for (uint256 i = kickoffTS; i <= block.timestamp + MAX_DURATION; i += TWO_WEEKS) { balance = add96(balance, currentBalance(account, i), "Staking::balanceOf: overflow"); } } /** * @notice Delegate votes from `msg.sender` which are locked until lockDate to `delegatee`. * @param delegatee The address to delegate votes to. * @param lockDate the date if the position to delegate. * */ function delegate(address delegatee, uint256 lockDate) public { return _delegate(msg.sender, delegatee, lockDate); } /** * @notice Delegates votes from signatory to a delegatee account. * Voting with EIP-712 Signatures. * * Voting power can be delegated to any address, and then can be used to * vote on proposals. A key benefit to users of by-signature functionality * is that they can create a signed vote transaction for free, and have a * trusted third-party spend rBTC(or ETH) on gas fees and write it to the * blockchain for them. * * The third party in this scenario, submitting the SOV-holder’s signed * transaction holds a voting power that is for only a single proposal. * The signatory still holds the power to vote on their own behalf in * the proposal if the third party has not yet published the signed * transaction that was given to them. * * @dev The signature needs to be broken up into 3 parameters, known as * v, r and s: * const r = '0x' + sig.substring(2).substring(0, 64); * const s = '0x' + sig.substring(2).substring(64, 128); * const v = '0x' + sig.substring(2).substring(128, 130); * * @param delegatee The address to delegate votes to. * @param lockDate The date until which the position is locked. * @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 lockDate, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { /** * @dev The DOMAIN_SEPARATOR is a hash that uniquely identifies a * smart contract. It is built from a string denoting it as an * EIP712 Domain, the name of the token contract, the version, * the chainId in case it changes, and the address that the * contract is deployed at. * */ bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); /// @dev GovernorAlpha uses BALLOT_TYPEHASH, while Staking uses DELEGATION_TYPEHASH bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, lockDate, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); /// @dev Verify address is not null and PK is not null either. require(RSKAddrValidator.checkPKNotZero(signatory), "Staking::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Staking::delegateBySig: invalid nonce"); require(now <= expiry, "Staking::delegateBySig: signature expired"); return _delegate(signatory, delegatee, lockDate); } /** * @notice Get the current votes balance for a user account. * @param account The address to get votes balance. * @dev This is a wrapper to simplify arguments. The actual computation is * performed on WeightedStaking parent contract. * @return The number of current votes for a user account. * */ function getCurrentVotes(address account) external view returns (uint96) { return getPriorVotes(account, block.number - 1, block.timestamp); } /** * @notice Get the current number of tokens staked for a day. * @param lockedTS The timestamp to get the staked tokens for. * */ function getCurrentStakedUntil(uint256 lockedTS) external view returns (uint96) { uint32 nCheckpoints = numTotalStakingCheckpoints[lockedTS]; return nCheckpoints > 0 ? totalStakingCheckpoints[lockedTS][nCheckpoints - 1].stake : 0; } /** * @notice Set new delegatee. Move from user's current delegate to a new * delegatee the stake balance. * @param delegator The user address to move stake balance from its current delegatee. * @param delegatee The new delegatee. The address to move stake balance to. * @param lockedTS The lock date. * */ function _delegate( address delegator, address delegatee, uint256 lockedTS ) internal { address currentDelegate = delegates[delegator][lockedTS]; uint96 delegatorBalance = currentBalance(delegator, lockedTS); delegates[delegator][lockedTS] = delegatee; emit DelegateChanged(delegator, lockedTS, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance, lockedTS); } /** * @notice Move an amount of delegate stake from a source address to a * destination address. * @param srcRep The address to get the staked amount from. * @param dstRep The address to send the staked amount to. * @param amount The staked amount to move. * @param lockedTS The lock date. * */ function _moveDelegates( address srcRep, address dstRep, uint96 amount, uint256 lockedTS ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) _decreaseDelegateStake(srcRep, lockedTS, amount); if (dstRep != address(0)) _increaseDelegateStake(dstRep, lockedTS, amount); } } /** * @notice Retrieve CHAIN_ID of the executing chain. * * Chain identifier (chainID) introduced in EIP-155 protects transaction * included into one chain from being included into another chain. * Basically, chain identifier is an integer number being used in the * processes of signing transactions and verifying transaction signatures. * * @dev As of version 0.5.12, Solidity includes an assembly function * chainid() that provides access to the new CHAINID opcode. * * TODO: chainId is included in block. So you can get chain id like * block timestamp or block number: block.chainid; * */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @notice Allow the owner to set a new staking contract. * As a consequence it allows the stakers to migrate their positions * to the new contract. * @dev Doesn't have any influence as long as migrateToNewStakingContract * is not implemented. * @param _newStakingContract The address of the new staking contract. * */ function setNewStakingContract(address _newStakingContract) public onlyOwner { require(_newStakingContract != address(0), "can't reset the new staking contract to 0"); newStakingContract = _newStakingContract; } /** * @notice Allow the owner to set a fee sharing proxy contract. * We need it for unstaking with slashing. * @param _feeSharing The address of FeeSharingProxy contract. * */ function setFeeSharing(address _feeSharing) public onlyOwner { require(_feeSharing != address(0), "FeeSharing address shouldn't be 0"); feeSharing = IFeeSharingProxy(_feeSharing); } /** * @notice Allow the owner to set weight scaling. * We need it for unstaking with slashing. * @param _weightScaling The weight scaling. * */ function setWeightScaling(uint96 _weightScaling) public onlyOwner { require( MIN_WEIGHT_SCALING <= _weightScaling && _weightScaling <= MAX_WEIGHT_SCALING, "weight scaling doesn't belong to range [1, 9]" ); weightScaling = _weightScaling; } /** * @notice Allow a staker to migrate his positions to the new staking contract. * @dev Staking contract needs to be set before by the owner. * Currently not implemented, just needed for the interface. * In case it's needed at some point in the future, * the implementation needs to be changed first. * */ function migrateToNewStakingContract() public { require(newStakingContract != address(0), "there is no new staking contract set"); /// @dev implementation: /// @dev Iterate over all possible lock dates from now until now + MAX_DURATION. /// @dev Read the stake & delegate of the msg.sender /// @dev If stake > 0, stake it at the new contract until the lock date with the current delegate. } /** * @notice Allow the owner to unlock all tokens in case the staking contract * is going to be replaced * Note: Not reversible on purpose. once unlocked, everything is unlocked. * The owner should not be able to just quickly unlock to withdraw his own * tokens and lock again. * @dev Last resort. * */ function unlockAllTokens() public onlyOwner { allUnlocked = true; emit TokensUnlocked(SOVToken.balanceOf(address(this))); } /** * @notice Get list of stakes for a user account. * @param account The address to get stakes. * @return The arrays of dates and stakes. * */ function getStakes(address account) external view returns (uint256[] memory dates, uint96[] memory stakes) { uint256 latest = timestampToLockDate(block.timestamp + MAX_DURATION); /// @dev Calculate stakes. uint256 count = 0; /// @dev We need to iterate from first possible stake date after deployment to the latest from current time. for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) { if (currentBalance(account, i) > 0) { count++; } } dates = new uint256[](count); stakes = new uint96[](count); /// @dev We need to iterate from first possible stake date after deployment to the latest from current time. uint256 j = 0; for (uint256 i = kickoffTS + TWO_WEEKS; i <= latest; i += TWO_WEEKS) { uint96 balance = currentBalance(account, i); if (balance > 0) { dates[j] = i; stakes[j] = balance; j++; } } } /** * @notice Overrides default ApprovalReceiver._getToken function to * register SOV token on this contract. * @return The address of SOV token. * */ function _getToken() internal view returns (address) { return address(SOVToken); } /** * @notice Overrides default ApprovalReceiver._getSelectors function to * register stakeWithApproval selector on this contract. * @return The array of registered selectors on this contract. * */ function _getSelectors() internal view returns (bytes4[] memory) { bytes4[] memory selectors = new bytes4[](1); selectors[0] = this.stakeWithApproval.selector; return selectors; } }
* @notice Stake the given amount for the given duration of time. @param amount The number of tokens to stake. @param until Timestamp indicating the date until which to stake. @param stakeFor The address to stake the tokens for or 0x0 if staking for oneself. @param delegatee The address of the delegatee or 0x0 if there is none. /
) external { _stake(msg.sender, amount, until, stakeFor, delegatee, false); }
13,117,440
[ 1, 510, 911, 326, 864, 3844, 364, 326, 864, 3734, 434, 813, 18, 225, 3844, 1021, 1300, 434, 2430, 358, 384, 911, 18, 225, 3180, 8159, 11193, 326, 1509, 3180, 1492, 358, 384, 911, 18, 225, 384, 911, 1290, 1021, 1758, 358, 384, 911, 326, 2430, 364, 578, 374, 92, 20, 309, 384, 6159, 364, 5945, 19079, 18, 225, 7152, 73, 1021, 1758, 434, 326, 7152, 73, 578, 374, 92, 20, 309, 1915, 353, 6555, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13, 3903, 288, 203, 202, 202, 67, 334, 911, 12, 3576, 18, 15330, 16, 3844, 16, 3180, 16, 384, 911, 1290, 16, 7152, 73, 16, 629, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xe4A0623412CEC77aB94c71d93F2C262236D8738F/sources/contracts/Unifarm.sol
* 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/ 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
function _msgSender() internal view virtual override returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } }
765,002
[ 1, 2463, 326, 5793, 434, 333, 745, 18, 309, 326, 745, 22497, 3059, 3134, 13179, 364, 20099, 16, 327, 326, 2282, 5793, 18, 3541, 16, 327, 1375, 3576, 18, 15330, 8338, 1410, 506, 1399, 316, 326, 6835, 25651, 3560, 434, 1234, 18, 15330, 19, 2380, 333, 1634, 732, 5055, 716, 326, 5793, 353, 279, 13179, 364, 20099, 16, 1427, 732, 10267, 716, 326, 1142, 1731, 434, 1234, 18, 892, 854, 326, 13808, 5793, 1758, 18, 2608, 5793, 1758, 628, 326, 679, 434, 1234, 18, 892, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 3576, 12021, 1435, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1135, 261, 2867, 8843, 429, 325, 13, 203, 565, 288, 203, 3639, 309, 261, 3576, 18, 892, 18, 2469, 1545, 4248, 597, 353, 16950, 30839, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 19931, 288, 203, 7734, 325, 519, 699, 86, 12, 10525, 16, 745, 72, 3145, 6189, 12, 1717, 12, 1991, 13178, 554, 9334, 4200, 20349, 203, 5411, 289, 203, 5411, 327, 1234, 18, 15330, 31, 203, 3639, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint private totalRegisteredAirlines = 0; address authorizedCaller; //CONSTS uint8 private constant FOUNDING_AIRLINES = 4; uint256 private constant MEMBERSHIP_FEE = 10 ether; enum AirlineState { PendingApproval, // 0 Registered //1 } struct Airline { string name; AirlineState state; bool isFunded; uint256 minRequiredVotes; uint256 positiveReceivedVotes; uint256 balance; } struct Passenger{ uint256 balance; uint256 withdrawableBalance; } struct FlightInsurance{ uint256 totalInsurees; mapping(uint256 => address) passengerAddresses; mapping(address => uint256) insurancePaid; } mapping(address => Airline) private airlines; mapping(string => FlightInsurance) private flightInsurances; //string key = flight name/id mapping(address => Passenger) private passengers; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event dummyEvent(string text); event AirlineRegistered(string airlineName); event OperationalStatusChanged(bool status, address requestor); event AirlineFunded(address airline, uint256 amount, uint256 oldBalace, uint256 newBalance); event InsuranceBought(address passenger, uint256 amount, uint256 oldBalace, uint256 newBalance, uint256 totalInsurees, string airline); event InsuranceCredited(address passengerAddress, uint256 amount, uint256 newBalance, uint256 totalInsurees, string airline); event InsuranceWithdrawn(address toAddress, uint256 amount, uint256 newBalance); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(isOperational(), "Data Contract is currently not operational"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the airline to be an active member */ modifier requireActiveAirline(address addr) { if(totalRegisteredAirlines > 0){ require(isAirlineActive(addr), "Caller is not an active airline"); } _; } /** * @dev Modifier that requires the minimum amount is meet in order to activate an airline */ modifier requireMinimumFee() { require(msg.value >= MEMBERSHIP_FEE, "Amount sent is less than the membership fee"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Get airline status * * @return A bool stating wheter the airline is an active member */ function isAirlineActive(address airlineAddress) public view returns(bool) { bool retval = false; if((airlines[airlineAddress].isFunded) && (airlines[airlineAddress].state == AirlineState.Registered)) { retval = true; } return retval; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; emit OperationalStatusChanged(operational, msg.sender); } /** * @dev Gets the required votes to be accepted as a registered member * * @return A uint256 with the minimum required votes */ function getRequiredVotes() private view returns(uint256){ if(totalRegisteredAirlines < FOUNDING_AIRLINES){ return 0; } else{ return totalRegisteredAirlines.div(2); } } function getContractBalance() external view returns (uint256) { return address(this).balance; } function getTotalRegisteredAirlines() external view returns(uint256){ return totalRegisteredAirlines; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(string memory airlineName, address airlineAddress, address requestorAddress) external requireIsOperational requireActiveAirline(requestorAddress) { AirlineState newState; if(totalRegisteredAirlines < FOUNDING_AIRLINES){ newState = AirlineState.Registered; totalRegisteredAirlines = totalRegisteredAirlines.add(1); } else{ newState = AirlineState.PendingApproval; } airlines[airlineAddress] = Airline(airlineName, newState, false, getRequiredVotes(), 0, 0); emit AirlineRegistered(airlineName); } /** * @dev Retrieves the current status of a given airline * */ function fetchAirlineStatus(address airlineAddress) external view requireIsOperational returns( string memory name, uint256 state, bool isFunded, uint256 minRequiredVotes, uint256 positiveReceivedVotes, uint256 balance ) { FlightSuretyData.Airline memory airline = airlines[airlineAddress]; return(airline.name, uint256(airline.state), airline.isFunded, airline.minRequiredVotes, airline.positiveReceivedVotes, airline.balance); } /** * @dev Funds a given airline and tranfers the funds to the contract's balance * */ function fundAirline(address airlineAddress) external payable requireIsOperational requireMinimumFee { uint256 oldBalance = airlines[airlineAddress].balance; airlines[airlineAddress].balance = airlines[airlineAddress].balance.add(msg.value); airlines[airlineAddress].isFunded = true; emit AirlineFunded(airlineAddress, msg.value, oldBalance, airlines[airlineAddress].balance); } /** * @dev This function is to submit voting to approve a given airline * */ function approveAirline(address airlineToApprove, address requestorAddress) external requireIsOperational requireActiveAirline(requestorAddress) { require(airlineToApprove != requestorAddress, "Votes cannot be emited by the same candidate airline"); airlines[airlineToApprove].positiveReceivedVotes = airlines[airlineToApprove].positiveReceivedVotes.add(1); if (airlines[airlineToApprove].positiveReceivedVotes >= airlines[airlineToApprove].minRequiredVotes) { airlines[airlineToApprove].state = AirlineState.Registered; } } /** * @dev Buy insurance for a flight * */ function buy ( address passengerAddress, string memory flightNumber ) external payable requireIsOperational { //TODO: Add validation of top 1 Eth uint256 oldBalance = passengers[passengerAddress].balance; passengers[passengerAddress].balance = passengers[passengerAddress].balance.add(msg.value); uint256 newAddressIndex = flightInsurances[flightNumber].totalInsurees; flightInsurances[flightNumber].passengerAddresses[newAddressIndex] = passengerAddress; flightInsurances[flightNumber].insurancePaid[passengerAddress] = flightInsurances[flightNumber].insurancePaid[passengerAddress].add(msg.value); flightInsurances[flightNumber].totalInsurees = newAddressIndex.add(1); emit InsuranceBought(passengerAddress, msg.value, oldBalance, passengers[passengerAddress].balance, flightInsurances[flightNumber].totalInsurees, flightNumber); } /** * @dev Credits payouts to insurees */ function creditInsurees ( string memory flightNumber ) external requireIsOperational { uint256 _addressIndex = flightInsurances[flightNumber].totalInsurees; address _passengerAddress; uint256 _insurancePaid; uint256 _insuranceWithdrawableAmount; for(uint256 i=0; i<_addressIndex; i++){ //cleans the insurance data _passengerAddress = flightInsurances[flightNumber].passengerAddresses[i]; _insurancePaid = flightInsurances[flightNumber].insurancePaid[_passengerAddress]; flightInsurances[flightNumber].insurancePaid[_passengerAddress] = _insurancePaid.sub(_insurancePaid); //moves the payout to the withdrawable balance passengers[_passengerAddress].balance = passengers[_passengerAddress].balance.sub(_insurancePaid); passengers[_passengerAddress].withdrawableBalance = passengers[_passengerAddress].withdrawableBalance.mul(150) / 100; emit InsuranceCredited(_passengerAddress, passengers[_passengerAddress].withdrawableBalance, passengers[_passengerAddress].balance, _addressIndex, //total insurees paid out flightNumber); } //resets the mapping flightInsurances[flightNumber].totalInsurees = 0; } /** * @dev Transfers eligible payout funds to insuree * */ function pay (address toAddress ) external payable requireIsOperational { uint withdrawableBalance = passengers[toAddress].balance; passengers[toAddress].balance = 0; (bool sent, bytes memory data) = toAddress.call{value: withdrawableBalance}(""); require(sent, "Failed to send Ether"); emit InsuranceWithdrawn(toAddress, withdrawableBalance, passengers[toAddress].balance); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ fallback() external payable requireIsOperational { } }
* @dev This function is to submit voting to approve a given airline/
function approveAirline(address airlineToApprove, address requestorAddress) external requireIsOperational requireActiveAirline(requestorAddress) { require(airlineToApprove != requestorAddress, "Votes cannot be emited by the same candidate airline"); airlines[airlineToApprove].positiveReceivedVotes = airlines[airlineToApprove].positiveReceivedVotes.add(1); if (airlines[airlineToApprove].positiveReceivedVotes >= airlines[airlineToApprove].minRequiredVotes) { airlines[airlineToApprove].state = AirlineState.Registered; } }
12,699,510
[ 1, 2503, 445, 353, 358, 4879, 331, 17128, 358, 6617, 537, 279, 864, 23350, 1369, 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 ]
[ 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, 6617, 537, 29752, 1369, 12, 2867, 23350, 1369, 774, 12053, 537, 16, 1758, 590, 280, 1887, 13, 203, 4766, 565, 3903, 203, 4766, 565, 2583, 2520, 2988, 287, 203, 4766, 565, 2583, 3896, 29752, 1369, 12, 2293, 280, 1887, 13, 203, 565, 288, 203, 3639, 2583, 12, 1826, 1369, 774, 12053, 537, 480, 590, 280, 1887, 16, 315, 29637, 2780, 506, 3626, 329, 635, 326, 1967, 5500, 23350, 1369, 8863, 7010, 3639, 23350, 3548, 63, 1826, 1369, 774, 12053, 537, 8009, 21094, 8872, 29637, 273, 23350, 3548, 63, 1826, 1369, 774, 12053, 537, 8009, 21094, 8872, 29637, 18, 1289, 12, 21, 1769, 203, 203, 3639, 309, 261, 1826, 3548, 63, 1826, 1369, 774, 12053, 537, 8009, 21094, 8872, 29637, 1545, 23350, 3548, 63, 1826, 1369, 774, 12053, 537, 8009, 1154, 3705, 29637, 13, 203, 3639, 288, 203, 5411, 23350, 3548, 63, 1826, 1369, 774, 12053, 537, 8009, 2019, 273, 432, 481, 1369, 1119, 18, 10868, 31, 7010, 3639, 289, 203, 565, 289, 203, 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 ]
// File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/babyzuki/ERC721A.sol pragma solidity ^0.8.0; interface IOwnershipData{ function getOwnershipData(uint256 tokenId) external view returns (address _address, uint64 _timestamp); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/babyzuki/contracts.sol pragma solidity ^0.8.0; contract BBZOrigin is Ownable, ERC721A, ReentrancyGuard, IOwnershipData { struct MintConfig { uint256 dnmAmount; bool groupAActive; uint256 groupAPrice; bool groupBActive; uint256 groupBPrice; bool groupCActive; uint256 groupCPrice; } MintConfig public config; mapping(address => uint256) public groupA; mapping(address => uint256) public groupB; string private baseTokenURI; constructor( uint256 collectionSize, uint256 dnmAmount ) ERC721A("BBZ Origin", "BBZORIGIN", 5, collectionSize) { config.dnmAmount = dnmAmount; config.groupAPrice = 0.1 ether; config.groupBPrice = 0.12 ether; config.groupCPrice = 0.14 ether; baseTokenURI = "https://d359zl9sgwt1qi.cloudfront.net/"; } modifier callerIsNotContract() { require(tx.origin == msg.sender, "The caller is another contract"); _; } /* DnM Related */ function mintDnM() external onlyOwner { uint256 numChunks = config.dnmAmount / maxBatchSize; for (uint256 i = 0; i < numChunks; i++) { _safeMint(msg.sender, maxBatchSize); } } function mintUnclaimed() external onlyOwner { for (uint256 i = currentIndex; i < collectionSize; i++) { _safeMint(msg.sender, 1); } } /* Manage */ function setGroupState(bool g1, bool g2, bool g3) external onlyOwner { config.groupAActive = g1; config.groupBActive = g2; config.groupCActive = g3; } function setGroupPrice(uint256 p1, uint256 p2, uint256 p3) external onlyOwner { config.groupAPrice = p1; config.groupBPrice = p2; config.groupCPrice = p3; } function withdrawETH() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } /* OG Mint */ function isOGMintActive() external view returns (bool) { return config.groupAActive; } function isInOgList() external view returns (bool) { return (groupA[msg.sender] > 0); } function mintOG(uint256 quantity) external payable callerIsNotContract { uint256 totalCost = uint256(config.groupAPrice) * quantity; require(config.groupAActive, "OG Sale is not active"); require(msg.value >= totalCost, "Not enough ETH"); require(groupA[msg.sender] >= quantity, "Not in OG list or already minted max amount"); require(currentIndex + quantity <= collectionSize, "Total tokens amount reached"); groupA[msg.sender] = groupA[msg.sender] - quantity; _safeMint(msg.sender, quantity); } function setOGList( address[] memory addresses, uint256[] memory numSlots ) external onlyOwner { require( addresses.length == numSlots.length, "Addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { groupA[addresses[i]] += numSlots[i]; } } /* WL Mint */ function isWLMintActive() external view returns (bool) { return config.groupBActive; } function isInWLList() external view returns (bool) { return (groupB[msg.sender] > 0); } function mintWL(uint256 quantity) external payable callerIsNotContract { uint256 totalCost = uint256(config.groupBPrice) * quantity; require(config.groupBActive, "WL Sale is not active"); require(msg.value >= totalCost, "Not enough ETH"); require(groupB[msg.sender] >= quantity, "Not in WL list or already minted max amount"); require(currentIndex + quantity <= collectionSize, "Total tokens amount reached"); groupB[msg.sender] = groupB[msg.sender] - quantity; _safeMint(msg.sender, quantity); } function setWLList( address[] memory addresses, uint256[] memory numSlots ) external onlyOwner { require( addresses.length == numSlots.length, "Addresses does not match numSlots length" ); for (uint256 i = 0; i < addresses.length; i++) { groupB[addresses[i]] += numSlots[i]; } } /* Public Mint */ function isPublicMintActive() external view returns (bool) { return config.groupCActive; } function mint(uint256 quantity) external payable callerIsNotContract { uint256 totalCost = uint256(config.groupCPrice) * quantity; require(config.groupCActive, "Public Sale is not active"); require(msg.value >= totalCost, "Not enough ETH"); require(currentIndex + quantity <= collectionSize, "Total tokens amount reached"); require(quantity <= 3, "Max mint amount is 3"); _safeMint(msg.sender, quantity); } /* Metadata */ function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string calldata baseURI) external onlyOwner { baseTokenURI = baseURI; } function setOwnersExplicit(uint256 quantity) external onlyOwner nonReentrant { _setOwnersExplicit(quantity); } function numberMinted(address owner) public view returns (uint256) { return _numberMinted(owner); } function getOwnershipData(uint256 tokenId) external override view returns (address _address, uint64 _timestamp) { TokenOwnership memory ownership = ownershipOf(tokenId); return (ownership.addr, ownership.startTimestamp); } } // File: contracts/babyzuki/bbz.sol pragma solidity 0.8.7; interface ISpendable{ function spend(address spender, uint256 amount) external returns (uint256); } contract BBZToken is ERC20, Ownable, ISpendable { struct ClaimableTokenData { bool active; uint256 defaultBonus; uint256 cycle; uint256 startTimestamp; mapping(uint256 => uint256) bonus; } mapping(address => ClaimableTokenData) claimableTokens; mapping(address => mapping(uint256 => uint256)) claims; address marketMaker; constructor(string memory name, string memory symbol) ERC20(name, symbol) { marketMaker = address(0); } function decimals() public view virtual override returns (uint8) { return 0; } function marketMakerAddress() public view returns (address) { return marketMaker; } function setMarketMakerAddress(address newAddress) external onlyOwner { marketMaker = newAddress; } function setCollectionBonus(address collectionAddress, bool active, uint256 timestamp, uint256 defaultBonus, uint256 cycle, uint256[] calldata tokenIds, uint256[] calldata bonus) external onlyOwner{ require(tokenIds.length == bonus.length, "Tokens ids are not compatible with bonuses"); require(cycle >= 60, "Cycle too low"); ClaimableTokenData storage tokenData = claimableTokens[collectionAddress]; tokenData.active = active; tokenData.defaultBonus = defaultBonus; tokenData.cycle = cycle; tokenData.startTimestamp = timestamp; for (uint256 i = 0; i < tokenIds.length; i++) { tokenData.bonus[tokenIds[i]] = bonus[i]; } } function setCollectionState(address collectionAddress, bool active, uint256 timestamp) external onlyOwner { ClaimableTokenData storage tokenData = claimableTokens[collectionAddress]; tokenData.active = active; tokenData.startTimestamp = timestamp; } function getTokenBonus(address collectionAddress, uint256 tokenId) external view returns (uint256){ ClaimableTokenData storage tokenData = claimableTokens[collectionAddress]; uint256 bonus = tokenData.bonus[tokenId]; return bonus == 0 ? tokenData.defaultBonus : bonus; } function claim(address tokenAddress, uint256[] calldata tokenIds) external { ClaimableTokenData storage tokenData = claimableTokens[tokenAddress]; require(tokenData.active, "Token is not activated for BBZ rewards."); _mint(msg.sender, _calculateAmountBeforeClaim(tokenData, tokenAddress, tokenIds)); } function claimableAmount(address tokenAddress, uint256[] calldata tokenIds) external view returns (uint256) { ClaimableTokenData storage tokenData = claimableTokens[tokenAddress]; require(tokenData.active, "Token is not activated for BBZ rewards."); return _calculateAmount(tokenData, tokenAddress, tokenIds); } function _calculateAmount(ClaimableTokenData storage tokenData, address tokenAddress, uint256[] memory tokenIds) private view returns (uint256){ IOwnershipData token = IOwnershipData(tokenAddress); uint256 amount = 0; mapping(uint256 => uint256) storage tokenClaims = claims[tokenAddress]; for (uint256 i = 0; i < tokenIds.length; i++) { (address tokenOwner, uint256 timestamp) = token.getOwnershipData(tokenIds[i]); require(tokenOwner == msg.sender, "You are not the owner of the NFT Token"); require(tokenOwner != address(0), "Token is not yet minted"); uint256 lastClaim = tokenClaims[tokenIds[i]]; if (lastClaim == 0 || lastClaim < timestamp){ lastClaim = timestamp; } if (lastClaim < tokenData.startTimestamp){ lastClaim = tokenData.startTimestamp; } uint256 diff = block.timestamp - lastClaim; uint256 bonus = tokenData.bonus[tokenIds[i]]; if (bonus == 0) { bonus = tokenData.defaultBonus; } amount = amount + ((diff / tokenData.cycle) * bonus); } return amount; } function _calculateAmountBeforeClaim(ClaimableTokenData storage tokenData, address tokenAddress, uint256[] memory tokenIds) private returns (uint256){ IOwnershipData token = IOwnershipData(tokenAddress); uint256 amount = 0; mapping(uint256 => uint256) storage tokenClaims = claims[tokenAddress]; for (uint256 i = 0; i < tokenIds.length; i++) { (address tokenOwner, uint256 timestamp) = token.getOwnershipData(tokenIds[i]); require(tokenOwner == msg.sender, "You are not the owner of the NFT Token"); require(tokenOwner != address(0), "Token is not yet minted"); uint256 lastClaim = tokenClaims[tokenIds[i]]; if (lastClaim == 0 || lastClaim < timestamp){ lastClaim = timestamp; } if (lastClaim < tokenData.startTimestamp){ lastClaim = tokenData.startTimestamp; } uint256 diff = block.timestamp - lastClaim; uint256 bonus = tokenData.bonus[tokenIds[i]]; if (bonus == 0) { bonus = tokenData.defaultBonus; } amount = amount + ((diff / tokenData.cycle) * bonus); tokenClaims[tokenIds[i]] = lastClaim + (diff / tokenData.cycle) * tokenData.cycle; } return amount; } // To be used by a market maker contract to burn users funds function spend(address from, uint256 amount) external override returns (uint256){ require(msg.sender == marketMaker, "Access denied"); require(balanceOf(from) >= amount, "Balance too low"); _burn(from, amount); return amount; } // For future use of manuall selling/negociating BBZ function mintTo(address to, uint256 amount) external onlyOwner { require(amount > 0, "Invalid amount"); _mint(to, amount); } } // File: contracts/babyzuki/marketplace.sol pragma solidity 0.8.7; struct Raffle { mapping(address => bool) participants; address[] addresses; uint256 participantsCount; mapping(address => bool) drawHelper; address[] winners; uint256 maxWinners; uint256 maxParticipants; uint256 endTimestamp; uint256 price; } contract Marketplace is Ownable { mapping(uint256 => Raffle) private raffles; mapping(address => uint256[]) private raffleEntries; uint256 public raffleCount; address private marketToken; constructor (address _marketToken) { marketToken = _marketToken; raffleCount = 0; } function createRaffle(uint256 _maxParticipants, uint256 _maxWinners, uint256 _endTimestamp, uint256 _price) external onlyOwner returns (uint256){ raffleCount++; Raffle storage raffle = raffles[raffleCount]; raffle.maxParticipants = _maxParticipants; raffle.maxWinners = _maxWinners; raffle.endTimestamp = _endTimestamp; raffle.price = _price; return raffleCount; } function joinRaffle(uint256 id) public { address participant = msg.sender; // get the required raffle Raffle storage raffle = raffles[id]; require(IERC20(marketToken).balanceOf(participant) >= raffle.price, "Not enought tokens"); // validate raffle status require(raffle.winners.length == 0, "Already picked winners"); require(!raffle.participants[participant], "Already participating"); require(raffle.participantsCount <= raffle.maxParticipants, "Reached max participants"); require(block.timestamp <= raffle.endTimestamp, "Too late to enter"); // deduct participation fee IERC20(marketToken).transferFrom(participant, owner(), raffle.price); raffle.participants[participant] = true; raffle.addresses.push(participant); raffle.participantsCount++; raffleEntries[participant].push(id); } function raffleDetails(uint256 id) public view returns (uint256, uint256, uint256) { require(raffleCount >= id); Raffle storage raffle = raffles[id]; return (raffle.participantsCount, raffle.price, raffle.maxParticipants); } function participating(address addr, uint256 id) external view returns (bool) { require(raffleCount >= id); Raffle storage raffle = raffles[id]; return raffle.participants[addr]; } function myRaffles() public view returns (uint256[] memory) { return raffleEntries[msg.sender]; } function canDrawRaffle(uint256 id) external view returns (bool) { require(raffleCount >= id, "Invalid raffle id"); Raffle storage raffle = raffles[id]; if (raffle.winners.length != 0) return false; if (raffle.participantsCount < raffle.maxParticipants) { if (block.timestamp < raffle.endTimestamp) return false; } return true; } function setRaffleWinners(uint256 id, uint256[] memory winners) external onlyOwner { require(raffleCount >= id, "Invalid raffle id"); Raffle storage raffle = raffles[id]; require(raffle.winners.length == 0, "Raffle already settled"); for (uint256 i = 0; i < winners.length; i++) { raffle.winners.push(raffle.addresses[winners[i]]); } } function raffleWinners(uint256 id) public view returns (address[] memory) { require(raffleCount >= id, "Invalid raffle id"); return raffles[id].winners; } }
get the required raffle validate raffle status deduct participation fee
function joinRaffle(uint256 id) public { address participant = msg.sender; Raffle storage raffle = raffles[id]; require(IERC20(marketToken).balanceOf(participant) >= raffle.price, "Not enought tokens"); require(raffle.winners.length == 0, "Already picked winners"); require(!raffle.participants[participant], "Already participating"); require(raffle.participantsCount <= raffle.maxParticipants, "Reached max participants"); require(block.timestamp <= raffle.endTimestamp, "Too late to enter"); IERC20(marketToken).transferFrom(participant, owner(), raffle.price); raffle.participants[participant] = true; raffle.addresses.push(participant); raffle.participantsCount++; raffleEntries[participant].push(id); }
13,438,664
[ 1, 588, 326, 1931, 767, 1403, 298, 1954, 767, 1403, 298, 1267, 11140, 853, 30891, 367, 14036, 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, 1233, 54, 7329, 298, 12, 11890, 5034, 612, 13, 1071, 288, 203, 3639, 1758, 14188, 273, 1234, 18, 15330, 31, 203, 3639, 534, 7329, 298, 2502, 767, 1403, 298, 273, 767, 1403, 1040, 63, 350, 15533, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 27151, 1345, 2934, 12296, 951, 12, 2680, 14265, 13, 1545, 767, 1403, 298, 18, 8694, 16, 315, 1248, 570, 83, 9540, 2430, 8863, 377, 203, 203, 3639, 2583, 12, 354, 1403, 298, 18, 8082, 9646, 18, 2469, 422, 374, 16, 315, 9430, 25534, 5657, 9646, 8863, 203, 3639, 2583, 12, 5, 354, 1403, 298, 18, 2680, 27620, 63, 2680, 14265, 6487, 315, 9430, 30891, 1776, 8863, 203, 3639, 2583, 12, 354, 1403, 298, 18, 2680, 27620, 1380, 1648, 767, 1403, 298, 18, 1896, 1988, 27620, 16, 315, 23646, 943, 22346, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 1648, 767, 1403, 298, 18, 409, 4921, 16, 315, 10703, 26374, 358, 6103, 8863, 203, 203, 3639, 467, 654, 39, 3462, 12, 27151, 1345, 2934, 13866, 1265, 12, 2680, 14265, 16, 3410, 9334, 767, 1403, 298, 18, 8694, 1769, 203, 203, 3639, 767, 1403, 298, 18, 2680, 27620, 63, 2680, 14265, 65, 273, 638, 31, 203, 3639, 767, 1403, 298, 18, 13277, 18, 6206, 12, 2680, 14265, 1769, 203, 3639, 767, 1403, 298, 18, 2680, 27620, 1380, 9904, 31, 203, 3639, 767, 1403, 298, 5400, 63, 2680, 14265, 8009, 6206, 12, 350, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x81373f4E8D0BD48bbE8842E9eE16dB7B60c20613/sources/src/interfaces/zeroliquid/IZeroLiquidErrors.sol
@title IZeroLiquidErrors @author ZeroLiquid @notice Specifies errors.
interface IZeroLiquidErrors { error UnsupportedToken(address token); error TokenDisabled(address token); error Undercollateralized(); error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue); error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss); error MintingLimitExceeded(uint256 amount, uint256 available); error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available); error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available); error SlippageExceeded(uint256 amount, uint256 minimumAmountOut); pragma solidity >=0.5.0; }
9,375,051
[ 1, 6867, 2439, 48, 18988, 350, 4229, 225, 12744, 48, 18988, 350, 225, 4185, 5032, 1334, 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, 5831, 467, 7170, 48, 18988, 350, 4229, 288, 203, 565, 555, 7221, 1345, 12, 2867, 1147, 1769, 203, 203, 565, 555, 3155, 8853, 12, 2867, 1147, 1769, 203, 203, 565, 555, 21140, 12910, 2045, 287, 1235, 5621, 203, 203, 565, 555, 13219, 620, 10069, 12, 2867, 2824, 1345, 16, 2254, 5034, 30844, 16, 2254, 5034, 4207, 6861, 620, 1769, 203, 203, 565, 555, 511, 8464, 10069, 12, 2867, 2824, 1345, 16, 2254, 5034, 8324, 16, 2254, 5034, 4207, 20527, 1769, 203, 203, 565, 555, 490, 474, 310, 3039, 10069, 12, 11890, 5034, 3844, 16, 2254, 5034, 2319, 1769, 203, 203, 565, 555, 868, 10239, 3039, 10069, 12, 2867, 6808, 1345, 16, 2254, 5034, 3844, 16, 2254, 5034, 2319, 1769, 203, 203, 565, 555, 511, 18988, 350, 367, 3039, 10069, 12, 2867, 6808, 1345, 16, 2254, 5034, 3844, 16, 2254, 5034, 2319, 1769, 203, 203, 565, 555, 348, 3169, 2433, 10069, 12, 11890, 5034, 3844, 16, 2254, 5034, 5224, 6275, 1182, 1769, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-11 */ // SPDX-License-Identifier: https://github.com/lendroidproject/protocol.2.0/blob/master/LICENSE.md // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.7.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.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.7.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/Pausable.sol pragma solidity ^0.7.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/heartbeat/Pacemaker.sol pragma solidity 0.7.5; /** @title Pacemaker @author Lendroid Foundation @notice Smart contract based on which various events in the Protocol take place @dev Audit certificate : https://certificate.quantstamp.com/view/lendroid-whalestreet */ // solhint-disable-next-line abstract contract Pacemaker { using SafeMath for uint256; uint256 constant public HEART_BEAT_START_TIME = 1607212800;// 2020-12-06 00:00:00 UTC (UTC +00:00) uint256 constant public EPOCH_PERIOD = 8 hours; /** @notice Displays the epoch which contains the given timestamp @return uint256 : Epoch value */ function epochFromTimestamp(uint256 timestamp) public pure returns (uint256) { if (timestamp > HEART_BEAT_START_TIME) { return timestamp.sub(HEART_BEAT_START_TIME).div(EPOCH_PERIOD).add(1); } return 0; } /** @notice Displays timestamp when a given epoch began @return uint256 : Epoch start time */ function epochStartTimeFromTimestamp(uint256 timestamp) public pure returns (uint256) { if (timestamp <= HEART_BEAT_START_TIME) { return HEART_BEAT_START_TIME; } else { return HEART_BEAT_START_TIME.add((epochFromTimestamp(timestamp).sub(1)).mul(EPOCH_PERIOD)); } } /** @notice Displays timestamp when a given epoch will end @return uint256 : Epoch end time */ function epochEndTimeFromTimestamp(uint256 timestamp) public pure returns (uint256) { if (timestamp < HEART_BEAT_START_TIME) { return HEART_BEAT_START_TIME; } else if (timestamp == HEART_BEAT_START_TIME) { return HEART_BEAT_START_TIME.add(EPOCH_PERIOD); } else { return epochStartTimeFromTimestamp(timestamp).add(EPOCH_PERIOD); } } /** @notice Calculates current epoch value from the block timestamp @dev Calculates the nth 8-hour window frame since the heartbeat's start time @return uint256 : Current epoch value */ function currentEpoch() public view returns (uint256) { return epochFromTimestamp(block.timestamp);// solhint-disable-line not-rely-on-time } } // File: contracts/IToken0.sol pragma solidity 0.7.5; /** * @dev Required interface of a Token0 compliant contract. */ interface IToken0 is IERC20 { function mint(address account, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // File: contracts/IVault.sol pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Required interface of a Vault compliant contract. */ interface IVault { function lockVault() external; function unlockVault() external; function safeAddAsset(address[] calldata tokenAddresses, uint256[] calldata tokenIds, string[] calldata categories) external; function safeTransferAsset(uint256[] calldata assetIds) external; function escapeHatchERC721(address tokenAddress, uint256 tokenId) external; function setDecentralandOperator(address registryAddress, address operatorAddress, uint256 assetId) external; function transferOwnership(address newOwner) external; function totalAssetSlots() external view returns (uint256); function onERC721Received(address, uint256, bytes memory) external pure returns (bytes4); } // File: contracts/SimpleBuyout.sol pragma solidity 0.7.5; /** @title SimpleBuyout @author Lendroid Foundation @notice Smart contract representing a NFT bundle buyout @dev Audit certificate : Pending */ contract SimpleBuyout is Ownable, Pacemaker, Pausable { using SafeERC20 for IERC20; using SafeERC20 for IToken0; using SafeMath for uint256; using Address for address; enum BuyoutStatus { ENABLED, ACTIVE, REVOKED, ENDED } BuyoutStatus public status; IToken0 public token0; //// admin IERC20 public token2; uint256 public startThreshold; uint256[4] public epochs;// [startEpoch, endEpoch, durationInEpochs, bidIntervalInEpochs] //// vault IVault public vault; //// governance uint256 public stopThresholdPercent; uint256 public currentBidToken0Staked; mapping (address => uint256) public token0Staked; //// end user address public highestBidder; uint256[3] public highestBidValues;// [highestBid, highestToken0Bid, highestToken2Bid] //// bid and veto count uint256 public currentBidId; mapping (address => uint256) public lastVetoedBidId; //// redeem uint256 public redeemToken2Amount; //// prevent flash loan attacks on veto/withdrawVeto logic mapping (address => uint256) public lastVetoedBlockNumber; uint256 constant public MINIMUM_BID_PERCENTAGE_INCREASE_ON_VETO = 108; uint256 constant public MINIMUM_BID_TOKEN0_PERCENTAGE_REQUIRED = 1; // Events that will be emitted on changes. event HighestBidIncreased(address bidder, uint256 amount); event BuyoutStarted(address bidder, uint256 amount); event BuyoutRevoked(uint256 amount); event BuyoutEnded(address bidder, uint256 amount); // solhint-disable-next-line func-visibility constructor(address token0Address, address token2Address, address vaultAddress, uint256[4] memory uint256Values) { // input validations require(token0Address.isContract(), "{enableBuyout} : invalid token0Address"); require(token2Address.isContract(), "{enableBuyout} : invalid token2Address"); require(vaultAddress.isContract(), "{enableBuyout} : invalid vaultAddress"); require(uint256Values[0] > 0, "{enableBuyout} : startThreshold cannot be zero"); require(uint256Values[1] > 0, "{enableBuyout} : durationInEpochs cannot be zero"); // uint256Values[1], aka, bidIntervalInEpochs can be zero, so no checks required. require(uint256Values[3] > 0 && uint256Values[3] <= 100, "{enableBuyout} : stopThresholdPercent should be between 1 and 100"); // set values token0 = IToken0(token0Address); token2 = IERC20(token2Address); vault = IVault(vaultAddress); startThreshold = uint256Values[0]; epochs[2] = uint256Values[1]; epochs[3] = uint256Values[2]; stopThresholdPercent = uint256Values[3]; status = BuyoutStatus.ENABLED; } function togglePause(bool pause) external onlyOwner { if (pause) { _pause(); } else { _unpause(); } } function transferVaultOwnership(address newOwner) external onlyOwner whenPaused { require(newOwner != address(0), "{transferVaultOwnership} : invalid newOwner"); // transfer ownership of Vault to newOwner vault.transferOwnership(newOwner); } function placeBid(uint256 totalBidAmount, uint256 token2Amount) external whenNotPaused { // verify buyout has not ended require(status != BuyoutStatus.ENDED, "{placeBid} : buyout has ended"); // verify token0 and token2 amounts are sufficient to place bid require(totalBidAmount > startThreshold, "{placeBid} : totalBidAmount does not meet minimum threshold"); require(token2.balanceOf(msg.sender) >= token2Amount, "{placeBid} : insufficient token2 balance"); require(totalBidAmount > highestBidValues[0], "{placeBid} : there already is a higher bid"); uint256 token0Amount = requiredToken0ToBid(totalBidAmount, token2Amount); require(token0.balanceOf(msg.sender) >= token0Amount, "{placeBid} : insufficient token0 balance"); require(token0Amount >= token0.totalSupply().mul(MINIMUM_BID_TOKEN0_PERCENTAGE_REQUIRED).div(100), "{placeBid} : token0Amount should be at least 5% of token0 totalSupply"); // increment bid number and reset veto count currentBidId = currentBidId.add(1); currentBidToken0Staked = 0; // update endEpoch if (status == BuyoutStatus.ACTIVE) { // already active require(currentEpoch() <= epochs[1], "{placeBid} : buyout end epoch has been surpassed"); epochs[1] = currentEpoch().add(epochs[3]); } else { // activate buyout process if applicable status = BuyoutStatus.ACTIVE; epochs[1] = currentEpoch().add(epochs[2]); } // set startEpoch epochs[0] = currentEpoch(); // return highest bid to previous bidder if (highestBidValues[1] > 0) { token0.safeTransfer(highestBidder, highestBidValues[1]); } if (highestBidValues[2] > 0) { token2.safeTransfer(highestBidder, highestBidValues[2]); } // set sender as highestBidder and totalBidAmount as highestBidValues[0] highestBidder = msg.sender; highestBidValues[0] = totalBidAmount; highestBidValues[1] = token0Amount; highestBidValues[2] = token2Amount; // transfer token0 and token2 to this contract token0.safeTransferFrom(msg.sender, address(this), token0Amount); token2.safeTransferFrom(msg.sender, address(this), token2Amount); // send notification emit HighestBidIncreased(msg.sender, totalBidAmount); } function veto(uint256 token0Amount) external whenNotPaused { require(token0Amount > 0, "{veto} : token0Amount cannot be zero"); token0Staked[msg.sender] = token0Staked[msg.sender].add(token0Amount); uint256 vetoAmount = lastVetoedBidId[msg.sender] == currentBidId ? token0Amount : token0Staked[msg.sender]; _veto(msg.sender, vetoAmount); token0.safeTransferFrom(msg.sender, address(this), token0Amount); } function extendVeto() external whenNotPaused { uint256 token0Amount = token0Staked[msg.sender]; require(token0Amount > 0, "{extendVeto} : no staked token0Amount"); require(lastVetoedBidId[msg.sender] != currentBidId, "{extendVeto} : already vetoed"); _veto(msg.sender, token0Amount); } function withdrawStakedToken0(uint256 token0Amount) external { require(lastVetoedBlockNumber[msg.sender] < block.number, "{withdrawStakedToken0} : Flash attack!"); require(token0Amount > 0, "{withdrawStakedToken0} : token0Amount cannot be zero"); require(token0Staked[msg.sender] >= token0Amount, "{withdrawStakedToken0} : token0Amount cannot exceed staked amount"); // ensure Token0 cannot be unstaked if users veto on current bid has not expired if ((status == BuyoutStatus.ACTIVE) && (currentEpoch() <= epochs[1])) { // already active require(lastVetoedBidId[msg.sender] != currentBidId, "{withdrawStakedToken0} : cannot unstake until veto on current bid expires"); } token0Staked[msg.sender] = token0Staked[msg.sender].sub(token0Amount); token0.safeTransfer(msg.sender, token0Amount); } function endBuyout() external whenNotPaused { // solhint-disable-next-line not-rely-on-time require(currentEpoch() > epochs[1], "{endBuyout} : end epoch has not yet been reached"); require(status != BuyoutStatus.ENDED, "{endBuyout} : buyout has already ended"); require(highestBidder != address(0), "{endBuyout} : buyout does not have highestBidder"); // additional safety checks require(((highestBidValues[1] > 0) || (highestBidValues[2] > 0)), "{endBuyout} : highestBidder deposits cannot be 0"); // set status status = BuyoutStatus.ENDED; redeemToken2Amount = highestBidValues[2]; highestBidValues[2] = 0; // burn token0Amount if (highestBidValues[1] > 0) { token0.burn(highestBidValues[1]); } // transfer ownership of Vault to highestBidder vault.transferOwnership(highestBidder); emit BuyoutEnded(highestBidder, highestBidValues[0]); } function withdrawBid() external whenPaused { require(highestBidder == msg.sender, "{withdrawBid} : sender is not highestBidder"); _resetHighestBidDetails(); } function redeem(uint256 token0Amount) external { require(status == BuyoutStatus.ENDED, "{redeem} : redeem has not yet been enabled"); require(token0.balanceOf(msg.sender) >= token0Amount, "{redeem} : insufficient token0 amount"); require(token0Amount > 0, "{redeem} : token0 amount cannot be zero"); uint256 token2Amount = token2AmountRedeemable(token0Amount); redeemToken2Amount = redeemToken2Amount.sub(token2Amount); // burn token0Amount token0.burnFrom(msg.sender, token0Amount); // send token2Amount token2.safeTransfer(msg.sender, token2Amount); } function token2AmountRedeemable(uint256 token0Amount) public view returns (uint256) { return token0Amount.mul(redeemToken2Amount).div(token0.totalSupply()); } function requiredToken0ToBid(uint256 totalBidAmount, uint256 token2Amount) public view returns (uint256) { uint256 token0Supply = token0.totalSupply(); require(token2Amount <= totalBidAmount, "{requiredToken0ToBid} : token2Amount cannot exceed totalBidAmount"); // token2Amount = threshold * ( (totalToken0Supply - token0Amount) / totalToken0Supply ) return token0Supply .mul( totalBidAmount .sub(token2Amount) ).div(totalBidAmount); } function _resetHighestBidDetails() internal { uint256 token0Amount = highestBidValues[1]; uint256 token2Amount = highestBidValues[2]; if (token0Amount > 0) { token0.safeTransfer(highestBidder, token0Amount); } if (token2Amount > 0) { token2.safeTransfer(highestBidder, token2Amount); } // reset highestBidder highestBidder = address(0); // reset highestBidValues highestBidValues[0] = 0; highestBidValues[1] = 0; highestBidValues[2] = 0; } function _veto(address sender, uint256 token0Amount) internal { // verify buyout has not ended require(( (status == BuyoutStatus.ACTIVE) && (currentEpoch() >= epochs[0]) && (currentEpoch() <= epochs[1]) ), "{_veto} : buyout is not active"); lastVetoedBlockNumber[sender] = block.number; lastVetoedBidId[sender] = currentBidId; uint256 updatedCurrentBidToken0Staked = currentBidToken0Staked.add(token0Amount); if (updatedCurrentBidToken0Staked < stopThresholdPercent.mul(token0.totalSupply().div(100))) { currentBidToken0Staked = updatedCurrentBidToken0Staked; } else { currentBidToken0Staked = 0; // increase startThreshold by 8% of last bid startThreshold = highestBidValues[0].mul(MINIMUM_BID_PERCENTAGE_INCREASE_ON_VETO).div(100); // reset endEpoch epochs[1] = 0; // set status status = BuyoutStatus.REVOKED; _resetHighestBidDetails(); emit BuyoutRevoked(updatedCurrentBidToken0Staked); } } }
solhint-disable-next-line not-rely-on-time additional safety checks set status burn token0Amount
function endBuyout() external whenNotPaused { require(((highestBidValues[1] > 0) || (highestBidValues[2] > 0)), status = BuyoutStatus.ENDED; redeemToken2Amount = highestBidValues[2]; highestBidValues[2] = 0; if (highestBidValues[1] > 0) { token0.burn(highestBidValues[1]); } emit BuyoutEnded(highestBidder, highestBidValues[0]); }
10,759,235
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 3312, 24179, 4271, 444, 1267, 18305, 1147, 20, 6275, 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, 679, 38, 9835, 659, 1435, 3903, 1347, 1248, 28590, 288, 203, 3639, 2583, 12443, 12, 8766, 395, 17763, 1972, 63, 21, 65, 405, 374, 13, 747, 261, 8766, 395, 17763, 1972, 63, 22, 65, 405, 374, 13, 3631, 203, 3639, 1267, 273, 605, 9835, 659, 1482, 18, 22088, 31, 203, 3639, 283, 24903, 1345, 22, 6275, 273, 9742, 17763, 1972, 63, 22, 15533, 203, 3639, 9742, 17763, 1972, 63, 22, 65, 273, 374, 31, 203, 3639, 309, 261, 8766, 395, 17763, 1972, 63, 21, 65, 405, 374, 13, 288, 203, 5411, 1147, 20, 18, 70, 321, 12, 8766, 395, 17763, 1972, 63, 21, 19226, 203, 3639, 289, 203, 203, 3639, 3626, 605, 9835, 659, 28362, 12, 8766, 395, 17763, 765, 16, 9742, 17763, 1972, 63, 20, 19226, 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 ]
./partial_match/1/0xdF1d7FD22aC3aB5171E275796f123224039f3b24/sources/src/v0.8/ccip/onRamp/EVM2EVMOnRamp.sol
@dev Same as TokenTransferFeeConfig token included so that an array of these can be passed in to setTokenTransferFeeConfig
struct TokenTransferFeeConfigArgs { }
4,303,745
[ 1, 8650, 487, 3155, 5912, 14667, 809, 1147, 5849, 1427, 716, 392, 526, 434, 4259, 848, 506, 2275, 316, 358, 22629, 5912, 14667, 809, 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 ]
[ 1, 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 ]
[ 1, 225, 1958, 3155, 5912, 14667, 809, 2615, 288, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; contract EncryptedSender { struct TopicData { // An (optional) public key used to encrypt messages for this topic. This is only necessary if the sender will // not have access to the public key offchain. bytes publicKey; // The encrypted message. bytes message; } struct Recipient { // This maps from a hash to the data for this topic. // Note: the hash is a hash of the "subject" or "topic" of the message. mapping(bytes32 => TopicData) topics; // This contains the set of all authorized senders for this recipient. mapping(address => bool) authorizedSenders; } mapping(address => Recipient) private recipients; /** * @notice Authorizes `sender` to send messages to the caller. */ function addAuthorizedSender(address sender) external { recipients[msg.sender].authorizedSenders[sender] = true; } /** * @notice Revokes `sender`'s authorization to send messages to the caller. */ function removeAuthorizedSender(address sender) external { recipients[msg.sender].authorizedSenders[sender] = false; } /** * @notice Gets the current stored message corresponding to `recipient` and `topicHash`. * @dev To decrypt messages (this requires access to the recipient's private keys), use the decryptMessage() * function in common/Crypto.js. */ function getMessage(address recipient, bytes32 topicHash) external view returns (bytes memory) { return recipients[recipient].topics[topicHash].message; } /** * @notice Gets the stored public key for a particular `recipient` and `topicHash`. Return value will be 0 length * if no public key has been set. * @dev Senders may need this public key to encrypt messages that only the `recipient` can read. If the public key * is communicated offchain, this field may be left empty. */ function getPublicKey(address recipient, bytes32 topicHash) external view returns (bytes memory) { return recipients[recipient].topics[topicHash].publicKey; } /** * @notice Sends `message` to `recipient_` categorized by a particular `topicHash`. This will overwrite any * previous messages sent to this `recipient` with this `topicHash`. * @dev To construct an encrypted message, use the encryptMessage() in common/Crypto.js. * The public key for the recipient can be obtained using the getPublicKey() method. */ function sendMessage(address recipient_, bytes32 topicHash, bytes memory message) public { Recipient storage recipient = recipients[recipient_]; require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to send to this recipient"); recipient.topics[topicHash].message = message; } function removeMessage(address recipient_, bytes32 topicHash) public { Recipient storage recipient = recipients[recipient_]; require(isAuthorizedSender(msg.sender, recipient_), "Not authorized to remove message"); delete recipient.topics[topicHash].message; } /** * @notice Sets the public key for this caller and topicHash. * @dev Note: setting the public key is optional - if the publicKey is communicated or can be derived offchain by * the sender, there is no need to set it here. Because there are no specific requirements for the publicKey, there * is also no verification of its validity other than its length. */ function setPublicKey(bytes memory publicKey, bytes32 topicHash) public { require(publicKey.length == 64, "Public key is the wrong length"); recipients[msg.sender].topics[topicHash].publicKey = publicKey; } /** * @notice Returns true if the `sender` is authorized to send to the `recipient`. */ function isAuthorizedSender(address sender, address recipient) public view returns (bool) { // Note: the recipient is always authorized to send messages to themselves. return recipients[recipient].authorizedSenders[sender] || recipient == sender; } } library FixedPoint { using SafeMath for uint; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint 10^77. uint private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint rawValue; } /** @dev Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. */ function fromUnscaledUint(uint a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(Unsigned memory a, uint b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** @dev Whether `a` is greater than `b`. */ function isGreaterThan(uint a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(Unsigned memory a, uint b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** @dev Whether `a` is less than `b`. */ function isLessThan(uint a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** @dev Adds two `Unsigned`s, reverting on overflow. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** @dev Adds an `Unsigned` to an unscaled uint, reverting on overflow. */ function add(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** @dev Subtracts two `Unsigned`s, reverting on underflow. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** @dev Subtracts an unscaled uint from an `Unsigned`, reverting on underflow. */ function sub(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** @dev Subtracts an `Unsigned` from an unscaled uint, reverting on underflow. */ function sub(uint a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** @dev Multiplies two `Unsigned`s, reverting on overflow. */ 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 uint ~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); } /** @dev Multiplies an `Unsigned` by an unscaled uint, reverting on overflow. */ function mul(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** @dev Divides with truncation two `Unsigned`s, reverting on overflow or division by 0. */ 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 uint 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)); } /** @dev Divides with truncation an `Unsigned` by an unscaled uint, reverting on division by 0. */ function div(Unsigned memory a, uint b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** @dev Divides with truncation an unscaled uint by an `Unsigned`, reverting on overflow or division by 0. */ function div(uint a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** @dev Raises an `Unsigned` to the power of an unscaled uint, reverting on overflow. E.g., `b=2` squares `a`. */ function pow(Unsigned memory a, uint b) internal pure returns (Unsigned memory output) { // TODO(ptare): Consider using the exponentiation by squaring technique instead: // https://en.wikipedia.org/wiki/Exponentiation_by_squaring output = fromUnscaledUint(1); for (uint i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint => Role) private roles; /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. */ function holdsRole(uint roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } require(false, "Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, exclusive role. */ function resetMember(uint roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. */ function getMember(uint roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the * managing role for `roleId`. */ function addMember(uint roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, shared role or if the caller is not a member of the * managing role for `roleId`. */ function removeMember(uint roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole(uint roleId, uint managingRoleId, address[] memory initialMembers) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require(roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role"); } /** * @notice Internal method to initialize a exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole(uint roleId, uint managingRoleId, address initialMember) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require(roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role"); } } interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Returns the time at which the user should expect the price to be resolved. 0 means the price has already * been resolved. */ function requestPrice(bytes32 identifier, uint time) external returns (uint expectedTime); /** * @notice Whether the Oracle provides prices for this identifier. */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); /** * @notice Whether the price for `identifier` and `time` is available. */ function hasPrice(bytes32 identifier, uint time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. */ function getPrice(bytes32 identifier, uint time) external view returns (int price); } interface RegistryInterface { /** * @dev Registers a new derivative. Only authorized derivative creators can call this method. */ function registerDerivative(address[] calldata counterparties, address derivativeAddress) external; /** * @dev Returns whether the derivative has been registered with the registry (and is therefore an authorized. * participant in the UMA system). */ function isDerivativeRegistered(address derivative) external view returns (bool isRegistered); /** * @dev Returns a list of all derivatives that are associated with a particular party. */ function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives); /** * @dev Returns all registered derivatives. */ function getAllRegisteredDerivatives() external view returns (address[] memory derivatives); } contract Registry is RegistryInterface, MultiRole { using SafeMath for uint; enum Roles { // The owner manages the set of DerivativeCreators. Owner, // Can register derivatives. DerivativeCreator } // Array of all derivatives that are approved to use the UMA Oracle. address[] private registeredDerivatives; // This enum is required because a WasValid state is required to ensure that derivatives cannot be re-registered. enum PointerValidity { Invalid, Valid } struct Pointer { PointerValidity valid; uint128 index; } // Maps from derivative address to a pointer that refers to that registered derivative in `registeredDerivatives`. mapping(address => Pointer) private derivativePointers; // Note: this must be stored outside of `registeredDerivatives` because mappings cannot be deleted and copied // like normal data. This could be stored in the Pointer struct, but storing it there would muddy the purpose // of the Pointer struct and break separation of concern between referential data and data. struct PartiesMap { mapping(address => bool) parties; } // Maps from derivative address to the set of parties that are involved in that derivative. mapping(address => PartiesMap) private derivativesToParties; event NewDerivativeRegistered(address indexed derivativeAddress, address indexed creator, address[] parties); constructor() public { _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); // Start with no derivative creators registered. _createSharedRole(uint(Roles.DerivativeCreator), uint(Roles.Owner), new address[](0)); } function registerDerivative(address[] calldata parties, address derivativeAddress) external onlyRoleHolder(uint(Roles.DerivativeCreator)) { // Create derivative pointer. Pointer storage pointer = derivativePointers[derivativeAddress]; // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double // registered). require(pointer.valid == PointerValidity.Invalid); pointer.valid = PointerValidity.Valid; registeredDerivatives.push(derivativeAddress); // No length check necessary because we should never hit (2^127 - 1) derivatives. pointer.index = uint128(registeredDerivatives.length.sub(1)); // Set up PartiesMap for this derivative. PartiesMap storage partiesMap = derivativesToParties[derivativeAddress]; for (uint i = 0; i < parties.length; i = i.add(1)) { partiesMap.parties[parties[i]] = true; } address[] memory partiesForEvent = parties; emit NewDerivativeRegistered(derivativeAddress, msg.sender, partiesForEvent); } function isDerivativeRegistered(address derivative) external view returns (bool isRegistered) { return derivativePointers[derivative].valid == PointerValidity.Valid; } function getRegisteredDerivatives(address party) external view returns (address[] memory derivatives) { // This is not ideal - we must statically allocate memory arrays. To be safe, we make a temporary array as long // as registeredDerivatives. We populate it with any derivatives that involve the provided party. Then, we copy // the array over to the return array, which is allocated using the correct size. Note: this is done by double // copying each value rather than storing some referential info (like indices) in memory to reduce the number // of storage reads. This is because storage reads are far more expensive than extra memory space (~100:1). address[] memory tmpDerivativeArray = new address[](registeredDerivatives.length); uint outputIndex = 0; for (uint i = 0; i < registeredDerivatives.length; i = i.add(1)) { address derivative = registeredDerivatives[i]; if (derivativesToParties[derivative].parties[party]) { // Copy selected derivative to the temporary array. tmpDerivativeArray[outputIndex] = derivative; outputIndex = outputIndex.add(1); } } // Copy the temp array to the return array that is set to the correct size. derivatives = new address[](outputIndex); for (uint j = 0; j < outputIndex; j = j.add(1)) { derivatives[j] = tmpDerivativeArray[j]; } } function getAllRegisteredDerivatives() external view returns (address[] memory derivatives) { return registeredDerivatives; } } library ResultComputation { using FixedPoint for FixedPoint.Unsigned; struct Data { // Maps price to number of tokens that voted for that price. mapping(int => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int currentMode; } /** * @dev Returns whether the result is resolved, and if so, what value it resolved to. `price` should be ignored if * `isResolved` is false. * @param minVoteThreshold Minimum number of tokens that must have been voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int price) { // TODO(ptare): Figure out where this parameter is supposed to come from. FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if (data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)) { // `modeThreshold` and `minVoteThreshold` are met, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @dev Adds a new vote to be used when computing the result. */ function addVote(Data storage data, int votePrice, FixedPoint.Unsigned memory numberTokens) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if (votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])) { data.currentMode = votePrice; } } /** * @dev Checks whether a `voteHash` is considered correct. Should only be called after a vote is resolved, i.e., * via `getResolvedPrice`. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @dev Gets the total number of tokens whose votes are considered correct. Should only be called after a vote is * resolved, i.e., via `getResolvedPrice`. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } contract Testable { // Is the contract being run on the test network. Note: this variable should be set on construction and never // modified. bool public isTest; uint private currentTime; constructor(bool _isTest) internal { isTest = _isTest; if (_isTest) { currentTime = now; // solhint-disable-line not-rely-on-time } } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(isTest); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. */ function setCurrentTime(uint _time) external onlyIfTest { currentTime = _time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. */ function getCurrentTime() public view returns (uint) { if (isTest) { return currentTime; } else { return now; // solhint-disable-line not-rely-on-time } } } contract Governor is MultiRole, Testable { using SafeMath for uint; enum Roles { // Can set the proposer. Owner, // Address that can make proposals. Proposer } struct Transaction { address to; uint value; bytes data; } struct Proposal { Transaction[] transactions; uint requestTime; } Finder private finder; Proposal[] public proposals; /** * @notice Emitted when a new proposal is created. */ event NewProposal(uint indexed id, Transaction[] transactions); /** * @notice Emitted when an existing proposal is executed. */ event ProposalExecuted(uint indexed id, uint transactionIndex); constructor(address _finderAddress, bool _isTest) public Testable(_isTest) { finder = Finder(_finderAddress); _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); _createExclusiveRole(uint(Roles.Proposer), uint(Roles.Owner), msg.sender); } /** * @notice Executes a proposed governance action that has been approved by voters. This can be called by anyone. */ function executeProposal(uint id, uint transactionIndex) external { Proposal storage proposal = proposals[id]; int price = _getVoting().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction storage transaction = proposal.transactions[transactionIndex]; require(transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous transaction has not been executed"); require(transaction.to != address(0), "Transaction has already been executed"); require(price != 0, "Cannot execute, proposal was voted down"); require(_executeCall(transaction.to, transaction.value, transaction.data), "Transaction execution failed"); // Delete the transaction. delete proposal.transactions[transactionIndex]; emit ProposalExecuted(id, transactionIndex); } /** * @notice Gets the total number of proposals (includes executed and non-executed). */ function numProposals() external view returns (uint) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * Note: after a proposal is executed, its data will be zeroed out. */ function getProposal(uint id) external view returns (Proposal memory proposal) { return proposals[id]; } /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions the list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that disallows structs arrays to be passed to * external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint(Roles.Proposer)) { uint id = proposals.length; uint time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add an element to the proposals array. proposals.length = proposals.length.add(1); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. proposal.transactions.length = transactions.length; for (uint i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The to address cannot be 0x0"); proposal.transactions[i] = transactions[i]; } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. Voting voting = _getVoting(); voting.addSupportedIdentifier(identifier); // Note: this check is only here to appease slither. require(voting.requestPrice(identifier, time) != ~uint(0), "Proposal will never be considered"); voting.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } function _constructIdentifier(uint id) private pure returns (bytes32 identifier) { bytes32 bytesId = _uintToBytes(id); return _addPrefix(bytesId, "Admin ", 6); } function _executeCall(address to, uint256 value, bytes memory data) private returns (bool success) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas, to, value, inputData, inputDataSize, 0, 0) } } function _getVoting() private view returns (Voting voting) { return Voting(finder.getImplementationAddress("Oracle")); } // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToBytes(uint v) private pure returns (bytes32 ret) { if (v == 0) { ret = "0"; } else { while (v > 0) { ret = ret >> 8; ret |= bytes32((v % 10) + 48) << (31 * 8); v /= 10; } } return ret; } function _addPrefix(bytes32 input, bytes32 prefix, uint prefixLength) private pure returns (bytes32 output) { bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } library VoteTiming { using SafeMath for uint; // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. enum Phase { Commit, Reveal } // Note: this MUST match the number of values in the enum above. uint private constant NUM_PHASES = 2; struct Data { uint roundId; uint roundStartTime; uint phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input and resets the round id and round * start time to 1 and 0 respectively. * @dev This method should generally only be run once, but it can also be used to reset the data structure to its * initial values. */ function init(Data storage data, uint phaseLength) internal { data.phaseLength = phaseLength; data.roundId = 1; data.roundStartTime = 0; } /** * @notice Gets the most recently stored round ID set by updateRoundId(). */ function getLastUpdatedRoundId(Data storage data) internal view returns (uint) { return data.roundId; } /** * @notice Determines whether time has advanced far enough to advance to the next voting round and update the * stored round id. */ function shouldUpdateRoundId(Data storage data, uint currentTime) internal view returns (bool) { (uint roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime); return data.roundId != roundId; } /** * @notice Updates the round id. Note: if shouldUpdateRoundId() returns false, this method will have no effect. */ function updateRoundId(Data storage data, uint currentTime) internal { (data.roundId, data.roundStartTime) = _getCurrentRoundIdAndStartTime(data, currentTime); } /** * @notice Computes what the stored round id would be if it were updated right now, but this method does not * commit the update. */ function computeCurrentRoundId(Data storage data, uint currentTime) internal view returns (uint roundId) { (roundId,) = _getCurrentRoundIdAndStartTime(data, currentTime); } /** * @notice Computes the current phase based only on the current time. */ function computeCurrentPhase(Data storage data, uint currentTime) internal view returns (Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return Phase(currentTime.div(data.phaseLength).mod(NUM_PHASES)); } /** * @notice Gets the end time of the current round or any round in the future. Note: this method will revert if * the roundId < getLastUpdatedRoundId(). */ function computeEstimatedRoundEndTime(Data storage data, uint roundId) internal view returns (uint) { // The add(1) is because we want the round end time rather than the start time, so it's really the start of // the next round. uint roundDiff = roundId.sub(data.roundId).add(1); uint roundLength = data.phaseLength.mul(NUM_PHASES); return data.roundStartTime.add(roundDiff.mul(roundLength)); } /** * @dev Computes an updated round id and round start time based on the current time. */ function _getCurrentRoundIdAndStartTime(Data storage data, uint currentTime) private view returns (uint roundId, uint startTime) { uint currentStartTime = data.roundStartTime; // Return current data if time has moved backwards. if (currentTime <= data.roundStartTime) { return (data.roundId, data.roundStartTime); } // Get the start of the round that currentTime would be a part of by flooring by roundLength. uint roundLength = data.phaseLength.mul(NUM_PHASES); startTime = currentTime.div(roundLength).mul(roundLength); // Only increment the round ID if the start time has changed. if (startTime > currentStartTime) { roundId = data.roundId.add(1); } else { roundId = data.roundId; } } } contract VotingInterface { struct PendingRequest { bytes32 identifier; uint time; } /** * @notice Commit your vote for a price request for `identifier` at `time`. * @dev (`identifier`, `time`) must correspond to a price request that's currently in the commit phase. `hash` * should be the keccak256 hash of the price you want to vote for and a `int salt`. Commits can be changed. */ function commitVote(bytes32 identifier, uint time, bytes32 hash) external; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price` and `salt` must match the latest `hash` that `commitVote()` was called with. Only the * committer can reveal their vote. */ function revealVote(bytes32 identifier, uint time, int price, int salt) external; /** * @notice Gets the queries that are being voted on this round. */ function getPendingRequests() external view returns (PendingRequest[] memory); /** * @notice Gets the current vote phase (commit or reveal) based on the current block time. */ function getVotePhase() external view returns (VoteTiming.Phase); /** * @notice Gets the current vote round id based on the current block time. */ function getCurrentRoundId() external view returns (uint); /** * @notice Retrieves rewards owed for a set of resolved price requests. */ function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory) public returns (FixedPoint.Unsigned memory); } 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; } } 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 { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } 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); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract 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; } } contract Finder is Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @dev Updates the address of the contract that implements `interfaceName`. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @dev Gets the address of the contract that implements the given `interfaceName`. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address implementationAddress) { implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "No implementation for interface found"); } } contract Voting is Testable, Ownable, OracleInterface, VotingInterface, EncryptedSender { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint time; // A map containing all votes for this price in various rounds. mapping(uint => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint index; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint time; int price; int salt; } struct Round { // Voting token snapshot ID for this round. If this is 0, no snapshot has been taken. uint snapshotId; // Inflation rate set for this round. FixedPoint.Unsigned inflationRate; } // Represents the status a price request has. enum RequestStatus { // Was never requested. NotRequested, // Is being voted on in the current round. Active, // Was resolved in a previous round. Resolved, // Is scheduled to be voted on in a future round. Future } // Maps round numbers to the rounds. mapping(uint => Round) private rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. These requests may be for future // rounds. bytes32[] private pendingPriceRequests; VoteTiming.Data private voteTiming; // The set of identifiers the oracle can provide verified prices for. mapping(bytes32 => bool) private supportedIdentifiers; // Percentage of the total token supply that must be used in a vote to create a valid price resolution. // 1 == 100%. FixedPoint.Unsigned private gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. Note: this value is used to set per-round inflation at the beginning // of each round. // 1 = 100% FixedPoint.Unsigned private inflationRate; // Reference to the voting token. VotingToken private votingToken; // Reference to the Finder. Finder private finder; // If non-zero, this contract has been migrated to this address. All voters and financial contracts should query the // new address only. address private migratedAddress; // Max value of an unsigned integer. uint constant private UINT_MAX = ~uint(0); event VoteCommitted(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time); event VoteRevealed( address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time, int price, uint numTokens ); event RewardsRetrieved(address indexed voter, uint indexed roundId, bytes32 indexed identifier, uint time, uint numTokens); event PriceRequestAdded(uint indexed votingRoundId, bytes32 indexed identifier, uint time); event PriceResolved(uint indexed resolutionRoundId, bytes32 indexed identifier, uint time, int price); event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /** * @notice Construct the Voting contract. * @param phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage percentage of the total token supply that must be used in a vote to create a valid price * resolution. * @param _isTest whether this contract is being constructed for the purpose of running automated tests. */ constructor( uint phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, address _votingToken, address _finder, bool _isTest ) public Testable(_isTest) { voteTiming.init(phaseLength); // TODO(#779): GAT percentage must be < 100% require(_gatPercentage.isLessThan(1)); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = Finder(_finder); } modifier onlyRegisteredDerivative() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress); } else { Registry registry = Registry(finder.getImplementationAddress("Registry")); // TODO(#779): Must be registered derivative require(registry.isDerivativeRegistered(msg.sender)); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0)); _; } function requestPrice(bytes32 identifier, uint time) external onlyRegisteredDerivative() returns (uint expectedTime) { uint blockTime = getCurrentTime(); // TODO(#779): Price request must be for a time in the past require(time <= blockTime); // TODO(#779): Price request for unsupported identifier require(supportedIdentifiers[identifier]); // Must ensure the round is updated here so the requested price will be voted on in the next commit cycle. _updateRound(blockTime); bytes32 priceRequestId = _encodePriceRequest(identifier, time); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return voteTiming.computeEstimatedRoundEndTime(currentRoundId); } else if (requestStatus == RequestStatus.Resolved) { return 0; } else if (requestStatus == RequestStatus.Future) { return voteTiming.computeEstimatedRoundEndTime(priceRequest.lastVotingRound); } // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); // Estimate the end of next round and return the time. return voteTiming.computeEstimatedRoundEndTime(nextRoundId); } function batchCommit(Commitment[] calldata commits) external { for (uint i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].hash); } else { commitAndPersistEncryptedVote( commits[i].identifier, commits[i].time, commits[i].hash, commits[i].encryptedVote); } } } function batchReveal(Reveal[] calldata reveals) external { for (uint i = 0; i < reveals.length; i++) { revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt); } } /** * @notice Disables this Voting contract in favor of the migrated one. */ function setMigrated(address newVotingAddress) external onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Adds the provided identifier as a supported identifier. Price requests using this identifier will be * succeed after this call. */ function addSupportedIdentifier(bytes32 identifier) external onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. Price requests using this identifier will no longer succeed * after this call. */ function removeSupportedIdentifier(bytes32 identifier) external onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } function isIdentifierSupported(bytes32 identifier) external view returns (bool) { return supportedIdentifiers[identifier]; } function hasPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (bool _hasPrice) { (_hasPrice, ,) = _getPriceOrError(identifier, time); } function getPrice(bytes32 identifier, uint time) external view onlyRegisteredDerivative() returns (int) { (bool _hasPrice, int price, string memory message) = _getPriceOrError(identifier, time); // TODO(#779): If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } function getPendingRequests() external view returns (PendingRequest[] memory pendingRequests) { uint blockTime = getCurrentTime(); uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that `isActive()`. PendingRequest[] memory unresolved = new PendingRequest[](pendingPriceRequests.length); uint numUnresolved = 0; for (uint i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequest( { identifier: priceRequest.identifier, time: priceRequest.time }); numUnresolved++; } } pendingRequests = new PendingRequest[](numUnresolved); for (uint i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } } function getVotePhase() external view returns (VoteTiming.Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } function getCurrentRoundId() external view returns (uint) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } function commitVote(bytes32 identifier, uint time, bytes32 hash) public onlyIfNotMigrated() { // TODO(#779): Committed hash of 0 is disallowed, choose a different salt require(hash != bytes32(0)); // Current time is required for all vote timing queries. uint blockTime = getCurrentTime(); // TODO(#779): Cannot commit while in the reveal phase require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Commit); // Should only update the round in the commit phase because a new round that's already in the reveal phase // would be wasted. _updateRound(blockTime); // At this point, the computed and last updated round ID should be equal. uint currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); // TODO(#779): Cannot commit on inactive request require(_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time); } function revealVote(bytes32 identifier, uint time, int price, int salt) public onlyIfNotMigrated() { uint blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == VoteTiming.Phase.Reveal, "Cannot reveal while in the commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the // round is over. uint roundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // 0 hashes are disallowed in the commit phase, so they indicate a different error. require(voteSubmission.commit != bytes32(0), "Cannot reveal an uncommitted or previously revealed hash"); require(keccak256(abi.encode(price, salt)) == voteSubmission.commit, "Committed hash doesn't match revealed price and salt"); delete voteSubmission.commit; // Get or create a snapshot for this round. uint snapshotId = _getOrCreateSnapshotId(roundId); // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); // Remove the stored message for this price request, if it exists. bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId)); removeMessage(msg.sender, topicHash); emit VoteRevealed(msg.sender, roundId, identifier, time, price, balance.rawValue); } function commitAndPersistEncryptedVote( bytes32 identifier, uint time, bytes32 hash, bytes memory encryptedVote ) public { commitVote(identifier, time, hash); uint roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); bytes32 topicHash = keccak256(abi.encode(identifier, time, roundId)); sendMessage(msg.sender, topicHash, encryptedVote); } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. */ function setInflationRate(FixedPoint.Unsigned memory _inflationRate) public onlyOwner { inflationRate = _inflationRate; } function retrieveRewards(address voterAddress, uint roundId, PendingRequest[] memory toRetrieve) public returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress); } uint blockTime = getCurrentTime(); _updateRound(blockTime); require(roundId < voteTiming.computeCurrentRoundId(blockTime)); Round storage round = rounds[roundId]; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned( votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned( votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; require(priceRequest.lastVotingRound == roundId, "Only retrieve rewards for votes resolved in same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)) { // The price was successfully resolved during the voter's last voting round, the voter revealed and was // correct, so they are elgible for a reward. FixedPoint.Unsigned memory correctTokens = voteInstance.resultComputation. getTotalCorrectlyVotedTokens(); // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div(correctTokens); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, reward.rawValue); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 0); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue)); } } /* * @dev Checks to see if there is a price that has or can be resolved for an (identifier, time) pair. * @returns a boolean noting whether a price is resolved, the price, and an error string if necessary. */ function _getPriceOrError(bytes32 identifier, uint time) private view returns (bool _hasPrice, int price, string memory err) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time); uint currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "The current voting round has not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price will be voted on in the future"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest(bytes32 identifier, uint time) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time)]; } function _encodePriceRequest(bytes32 identifier, uint time) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time)); } function _getOrCreateSnapshotId(uint roundId) private returns (uint) { Round storage round = rounds[roundId]; if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); } return round.snapshotId; } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int resolvedPrice) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve an unresolved price request"); // Delete the resolved price request from pendingPriceRequests. uint lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; delete pendingPriceRequests[lastIndex]; priceRequest.index = UINT_MAX; emit PriceResolved(priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice); } function _updateRound(uint blockTime) private { if (!voteTiming.shouldUpdateRoundId(blockTime)) { return; } uint nextVotingRoundId = voteTiming.computeCurrentRoundId(blockTime); // Set the round inflation rate to the current global inflation rate. rounds[nextVotingRoundId].inflationRate = inflationRate; // Update the stored round to the current one. voteTiming.updateRoundId(blockTime); } function _computeGat(uint roundId) private view returns (FixedPoint.Unsigned memory) { uint snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snaphotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice( _computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } } 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); } contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint value) external; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint value) external returns (bool); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Snapshot is ERC20 { using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; event Snapshot(uint256 id); // Creates a new snapshot id. Balances are only stored in snapshots on demand: unless a snapshot was taken, a // balance change will not be recorded. This means the extra added cost of storing snapshotted balances is only paid // when required, but is also flexible enough that it allows for e.g. daily snapshots. function snapshot() public returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } contract VotingToken is ExpandedIERC20, ERC20Snapshot, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } // Standard ERC20 metadata. string public constant name = "UMA Voting Token v1"; // solhint-disable-line const-name-snakecase string public constant symbol = "UMA"; // solhint-disable-line const-name-snakecase uint8 public constant decimals = 18; // solhint-disable-line const-name-snakecase constructor() public { _createExclusiveRole(uint(Roles.Owner), uint(Roles.Owner), msg.sender); _createSharedRole(uint(Roles.Minter), uint(Roles.Owner), new address[](0)); _createSharedRole(uint(Roles.Burner), uint(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. */ function mint(address recipient, uint value) external onlyRoleHolder(uint(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. */ function burn(uint value) external onlyRoleHolder(uint(Roles.Burner)) { _burn(msg.sender, value); } } library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } }
* @notice Updates the round id. Note: if shouldUpdateRoundId() returns false, this method will have no effect./
function updateRoundId(Data storage data, uint currentTime) internal { (data.roundId, data.roundStartTime) = _getCurrentRoundIdAndStartTime(data, currentTime); }
1,827,118
[ 1, 5121, 326, 3643, 612, 18, 3609, 30, 309, 1410, 1891, 11066, 548, 1435, 1135, 629, 16, 333, 707, 903, 1240, 1158, 5426, 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 ]
[ 1, 1, 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 ]
[ 1, 565, 445, 1089, 11066, 548, 12, 751, 2502, 501, 16, 2254, 6680, 13, 2713, 288, 203, 3639, 261, 892, 18, 2260, 548, 16, 501, 18, 2260, 13649, 13, 273, 389, 588, 3935, 11066, 548, 1876, 13649, 12, 892, 16, 6680, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "../pawn-p2p-v2/PawnLib.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "../pawn-nft/IPawnNFT.sol"; contract Exchange is Initializable, UUPSUpgradeable, AccessControlUpgradeable { mapping(address => address) public ListCryptoExchange; function initialize() public initializer { __AccessControl_init(); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) {} function supportsInterface(bytes4 interfaceId) public view override(AccessControlUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } // set dia chi cac token ( crypto) tuong ung voi dia chi chuyen doi ra USD tren chain link function setCryptoExchange( address _cryptoAddress, address _latestPriceAddress ) external onlyRole(DEFAULT_ADMIN_ROLE) { ListCryptoExchange[_cryptoAddress] = _latestPriceAddress; } function getLatestRoundData(AggregatorV3Interface getPriceToUSD) internal view returns (uint256, uint256) { (, int256 _price, , uint256 _timeStamp, ) = getPriceToUSD .latestRoundData(); require(_price > 0, "Negative or zero rate"); return (uint256(_price), _timeStamp); } // lay gia cua dong BNB function RateBNBwithUSD() internal view returns (uint256 price) { AggregatorV3Interface getPriceToUSD = AggregatorV3Interface( 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526 ); (price, ) = getLatestRoundData(getPriceToUSD); } // lay ti gia dong BNB + timestamp function RateBNBwithUSDAttimestamp() internal view returns (uint256 price, uint256 timeStamp) { AggregatorV3Interface getPriceToUSD = AggregatorV3Interface( 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526 ); (price, timeStamp) = getLatestRoundData(getPriceToUSD); } // lay gia cua cac crypto va token khac da duoc them vao ListcryptoExchange function getLatesPriceToUSD(address _adcrypto) internal view returns (uint256 price) { AggregatorV3Interface priceFeed = AggregatorV3Interface( ListCryptoExchange[_adcrypto] ); (price, ) = getLatestRoundData(priceFeed); } // lay ti gia va timestamp cua cac crypto va token da duoc them vao ListcryptoExchange function getRateAndTimestamp(address _adcrypto) internal view returns (uint256 price, uint256 timeStamp) { AggregatorV3Interface priceFeed = AggregatorV3Interface( ListCryptoExchange[_adcrypto] ); (price, timeStamp) = getLatestRoundData(priceFeed); } function calculateLoanAmountAndExchangeRate( Collateral memory _col, PawnShopPackage memory _pkg ) external view returns (uint256 loanAmount, uint256 exchangeRate) { (loanAmount, exchangeRate, , , ) = calcLoanAmountAndExchangeRate( _col.collateralAddress, _col.amount, _col.loanAsset, _pkg.loanToValue, _pkg.repaymentAsset ); } function calcLoanAmountAndExchangeRate( address collateralAddress, uint256 amount, address loanAsset, uint256 loanToValue, address repaymentAsset ) public view returns ( uint256 loanAmount, uint256 exchangeRate, uint256 collateralToUSD, uint256 rateLoanAsset, uint256 rateRepaymentAsset ) { if (collateralAddress == address(0)) { // If collateral address is address(0), check BNB exchange rate with USD // collateralToUSD = (uint256(RateBNBwithUSD()) * loanToValue * amount) / (100 * 10**5); (, uint256 ltvAmount) = SafeMathUpgradeable.tryMul( loanToValue, amount ); (, uint256 collRate) = SafeMathUpgradeable.tryMul( ltvAmount, uint256(RateBNBwithUSD()) ); (, uint256 collToUSD) = SafeMathUpgradeable.tryDiv( collRate, (100 * 10**5) ); collateralToUSD = collToUSD; } else { // If collateral address is not BNB, get latest price in USD of collateral crypto // collateralToUSD = (uint256(getLatesPriceToUSD(collateralAddress)) * loanToValue * amount) / (100 * 10**5); (, uint256 ltvAmount) = SafeMathUpgradeable.tryMul( loanToValue, amount ); (, uint256 collRate) = SafeMathUpgradeable.tryMul( ltvAmount, getLatesPriceToUSD(collateralAddress) ); (, uint256 collToUSD) = SafeMathUpgradeable.tryDiv( collRate, (100 * 10**5) ); collateralToUSD = collToUSD; } if (loanAsset == address(0)) { // get price of BNB in USD rateLoanAsset = RateBNBwithUSD(); } else { // get price in USD of crypto as loan asset rateLoanAsset = getLatesPriceToUSD(loanAsset); } (, uint256 lAmount) = SafeMathUpgradeable.tryDiv( collateralToUSD, rateLoanAsset ); // loanAmount = collateralToUSD / rateLoanAsset; // uint256 tempLoamAmount = lAmount / 10**13; // loanAmount = tempLoamAmount * 10**13; loanAmount = DivRound(lAmount); if (repaymentAsset == address(0)) { // get price in USD of BNB as repayment asset rateRepaymentAsset = RateBNBwithUSD(); } else { // get latest price in USD of crypto as repayment asset rateRepaymentAsset = getLatesPriceToUSD(repaymentAsset); } // calculate exchange rate (, uint256 xchange) = SafeMathUpgradeable.tryDiv( rateLoanAsset * 10**18, rateRepaymentAsset ); exchangeRate = xchange; } // calculate Rate of LoanAsset with repaymentAsset function exchangeRateofOffer(address _adLoanAsset, address _adRepayment) external view returns (uint256 exchangeRateOfOffer) { // exchangeRateOffer = loanAsset / repaymentAsset if (_adLoanAsset == address(0)) { // if LoanAsset is address(0) , check BNB exchange rate with BNB (, uint256 exRate) = SafeMathUpgradeable.tryDiv( RateBNBwithUSD() * 10**18, getLatesPriceToUSD(_adRepayment) ); exchangeRateOfOffer = exRate; } else { // all LoanAsset and repaymentAsset are crypto or token is different BNB (, uint256 exRate) = SafeMathUpgradeable.tryDiv( (getLatesPriceToUSD(_adLoanAsset) * 10**18), getLatesPriceToUSD(_adRepayment) ); exchangeRateOfOffer = exRate; } } //===========================================Tinh interest ======================================= // tinh tien lai cua moi ky: interest = loanAmount * interestByLoanDurationType //(interestByLoanDurationType = % lãi * số kì * loại kì / (365*100)) function calculateInterest( uint256 _remainingLoan, Contract memory _contract ) external view returns (uint256 interest) { uint256 _interestToUSD; uint256 _repaymentAssetToUSD; uint256 _interestByLoanDurationType; // tien lai if (_contract.terms.loanAsset == address(0)) { // neu loanAsset la dong BNB // interestToUSD = (uint256(RateBNBwithUSD()) *_contract.terms.loanAmount) * _contract.terms.interest; (, uint256 interestToAmount) = SafeMathUpgradeable.tryMul( _contract.terms.interest, _remainingLoan ); (, uint256 interestRate) = SafeMathUpgradeable.tryMul( interestToAmount, RateBNBwithUSD() ); (, uint256 itrestRate) = SafeMathUpgradeable.tryDiv( interestRate, (100 * 10**5) ); _interestToUSD = itrestRate; } else { // Neu loanAsset la cac dong crypto va token khac BNB // interestToUSD = (uint256(getLatesPriceToUSD(_contract.terms.loanAsset)) * _contract.terms.loanAmount) * _contractterms.interest; (, uint256 interestToAmount) = SafeMathUpgradeable.tryMul( _contract.terms.interest, _remainingLoan ); (, uint256 interestRate) = SafeMathUpgradeable.tryMul( interestToAmount, getLatesPriceToUSD(_contract.terms.loanAsset) ); (, uint256 itrestRate) = SafeMathUpgradeable.tryDiv( interestRate, (100 * 10**5) ); _interestToUSD = itrestRate; } // tinh tien lai cho moi ky thanh toan if (_contract.terms.repaymentCycleType == LoanDurationType.WEEK) { // neu thoi gian vay theo tuan thì L = loanAmount * interest * 7 /365 (, uint256 _interest) = SafeMathUpgradeable.tryDiv( (_interestToUSD * 7), 365 ); _interestByLoanDurationType = _interest; } else { // thoi gian vay theo thang thi L = loanAmount * interest * 30 /365 // _interestByLoanDurationType =(_contract.terms.interest * 30) / 365); (, uint256 _interest) = SafeMathUpgradeable.tryDiv( (_interestToUSD * 30), 365 ); _interestByLoanDurationType = _interest; } // tinh Rate cua dong repayment if (_contract.terms.repaymentAsset == address(0)) { // neu dong tra la BNB _repaymentAssetToUSD = RateBNBwithUSD(); } else { // neu dong tra kha BNB _repaymentAssetToUSD = getLatesPriceToUSD( _contract.terms.repaymentAsset ); } // tien lai theo moi kỳ tinh ra dong tra (, uint256 saInterest) = SafeMathUpgradeable.tryDiv( _interestByLoanDurationType, _repaymentAssetToUSD ); // uint256 tempInterest = saInterest / 10**13; // interest = tempInterest * 10**13; interest = DivRound(saInterest); } //=============================== Tinh penalty ===================================== // p = (p(n-1)) + (p(n-1) *(L)) + (L(n-1)*(p)) function calculatePenalty( PaymentRequest memory _paymentrequest, Contract memory _contract, uint256 _penaltyRate ) external pure returns (uint256 valuePenalty) { uint256 _interestOfPenalty; if (_contract.terms.repaymentCycleType == LoanDurationType.WEEK) { // neu ky vay theo tuan thi (L) = interest * 7 /365 //_interestByLoanDurationType =(_contract.terms.interest * 7) / (100 * 365); (, uint256 saInterestByLoanDurationType) = SafeMathUpgradeable .tryDiv((_contract.terms.interest * 7), 365); (, uint256 saPenaltyOfInterestRate) = SafeMathUpgradeable.tryMul( _paymentrequest.remainingPenalty, saInterestByLoanDurationType ); (, uint256 saPenaltyOfInterest) = SafeMathUpgradeable.tryDiv( saPenaltyOfInterestRate, (100 * 10**5) ); _interestOfPenalty = saPenaltyOfInterest; } else { // _interestByLoanDurationType =(_contract.terms.interest * 30) /(100 * 365); (, uint256 saInterestByLoanDurationType) = SafeMathUpgradeable .tryDiv(_contract.terms.interest * 30, 365); (, uint256 saPenaltyOfInterestRate) = SafeMathUpgradeable.tryMul( _paymentrequest.remainingPenalty, saInterestByLoanDurationType ); (, uint256 saPenaltyOfInterest) = SafeMathUpgradeable.tryDiv( saPenaltyOfInterestRate, (100 * 10**5) ); _interestOfPenalty = saPenaltyOfInterest; } // valuePenalty =(_paymentrequest.remainingPenalty +_paymentrequest.remainingPenalty *_interestByLoanDurationType +_paymentrequest.remainingInterest *_penaltyRate); // uint256 penalty = _paymentrequest.remainingInterest * _penaltyRate; (, uint256 penalty) = SafeMathUpgradeable.tryDiv( (_paymentrequest.remainingInterest * _penaltyRate), (100 * 10**5) ); uint256 _penalty = _paymentrequest.remainingPenalty + _interestOfPenalty + penalty; // uint256 tempPenalty = _penalty / 10**13; // valuePenalty = tempPenalty * 10**13; valuePenalty = DivRound(_penalty); } // lay Rate va thoi gian cap nhat ti gia do function RateAndTimestamp(Contract memory _contract) external view returns ( uint256 _collateralExchangeRate, uint256 _loanExchangeRate, uint256 _repaymemtExchangeRate, uint256 _rateUpdateTime ) { // Get exchange rate of collateral token if (_contract.terms.collateralAsset == address(0)) { ( _collateralExchangeRate, _rateUpdateTime ) = RateBNBwithUSDAttimestamp(); } else { (_collateralExchangeRate, _rateUpdateTime) = getRateAndTimestamp( _contract.terms.collateralAsset ); } // Get exchange rate of loan token if (_contract.terms.loanAsset == address(0)) { (_loanExchangeRate, _rateUpdateTime) = RateBNBwithUSDAttimestamp(); } else { (_loanExchangeRate, _rateUpdateTime) = getRateAndTimestamp( _contract.terms.loanAsset ); } // Get exchange rate of repayment token if (_contract.terms.repaymentAsset == address(0)) { ( _repaymemtExchangeRate, _rateUpdateTime ) = RateBNBwithUSDAttimestamp(); } else { (_repaymemtExchangeRate, _rateUpdateTime) = getRateAndTimestamp( _contract.terms.repaymentAsset ); } } // tinh ti gia cua repayment / collateralAsset va loanAsset / collateralAsset function collateralPerRepaymentAndLoanTokenExchangeRate( Contract memory _contract ) external view returns ( uint256 _collateralPerRepaymentTokenExchangeRate, uint256 _collateralPerLoanAssetExchangeRate ) { uint256 priceRepaymentAset; uint256 priceLoanAsset; uint256 priceCollateralAsset; if (_contract.terms.repaymentAsset == address(0)) { // neu repaymentAsset la BNB priceRepaymentAset = RateBNBwithUSD(); } else { // neu la cac dong khac priceRepaymentAset = getLatesPriceToUSD( _contract.terms.repaymentAsset ); } if (_contract.terms.loanAsset == address(0)) { // neu dong loan asset la BNB priceLoanAsset = RateBNBwithUSD(); } else { // cac dong khac priceLoanAsset = getLatesPriceToUSD(_contract.terms.loanAsset); } if (_contract.terms.collateralAsset == address(0)) { // neu collateralAsset la bnb priceCollateralAsset = RateBNBwithUSD(); } else { // la cac dong khac priceCollateralAsset = getLatesPriceToUSD( _contract.terms.collateralAsset ); } bool success; // tempCollateralPerRepaymentTokenExchangeRate = priceRepaymentAsset / priceCollateralAsset ( success, _collateralPerRepaymentTokenExchangeRate ) = SafeMathUpgradeable.tryDiv( (priceRepaymentAset * 10**10), priceCollateralAsset ); require(success, "Safe math: division by zero"); // _collateralPerRepaymentTokenExchangeRate = tempCollateralPerRepaymentTokenExchangeRate; // tempCollateralPerLoanAssetExchangeRate = priceLoanAsset / priceCollateralAsset (success, _collateralPerLoanAssetExchangeRate) = SafeMathUpgradeable .tryDiv((priceLoanAsset * 10**10), priceCollateralAsset); require(success, "Safe math: division by zero"); // _collateralPerLoanAssetExchangeRate = tempCollateralPerLoanAssetExchangeRate; } function DivRound(uint256 a) private pure returns (uint256) { // kiem tra so du khi chia 10**13. Neu lon hon 5 *10**12 khi chia xong thi lam tron len(+1) roi nhan lai voi 10**13 //con nho hon thi giu nguyen va nhan lai voi 10**13 uint256 tmp = a % 10**13; uint256 tm; if (tmp < 5 * 10**12) { tm = a / 10**13; } else { tm = a / 10**13 + 1; } uint256 rouding = tm * 10**13; return rouding; } }
If collateral address is address(0), check BNB exchange rate with USD collateralToUSD = (uint256(RateBNBwithUSD()) * loanToValue * amount) / (100 * 10**5); If collateral address is not BNB, get latest price in USD of collateral crypto collateralToUSD = (uint256(getLatesPriceToUSD(collateralAddress)) * loanToValue * amount) / (100 * 10**5); get price of BNB in USD get price in USD of crypto as loan asset get price in USD of BNB as repayment asset get latest price in USD of crypto as repayment asset
function calcLoanAmountAndExchangeRate( address collateralAddress, uint256 amount, address loanAsset, uint256 loanToValue, address repaymentAsset ) public view returns ( uint256 loanAmount, uint256 exchangeRate, uint256 collateralToUSD, uint256 rateLoanAsset, uint256 rateRepaymentAsset ) { if (collateralAddress == address(0)) { (, uint256 ltvAmount) = SafeMathUpgradeable.tryMul( loanToValue, amount ); (, uint256 collRate) = SafeMathUpgradeable.tryMul( ltvAmount, uint256(RateBNBwithUSD()) ); (, uint256 collToUSD) = SafeMathUpgradeable.tryDiv( collRate, (100 * 10**5) ); collateralToUSD = collToUSD; (, uint256 ltvAmount) = SafeMathUpgradeable.tryMul( loanToValue, amount ); (, uint256 collRate) = SafeMathUpgradeable.tryMul( ltvAmount, getLatesPriceToUSD(collateralAddress) ); (, uint256 collToUSD) = SafeMathUpgradeable.tryDiv( collRate, (100 * 10**5) ); collateralToUSD = collToUSD; } if (loanAsset == address(0)) { rateLoanAsset = RateBNBwithUSD(); rateLoanAsset = getLatesPriceToUSD(loanAsset); } (, uint256 lAmount) = SafeMathUpgradeable.tryDiv( collateralToUSD, rateLoanAsset ); if (repaymentAsset == address(0)) { rateRepaymentAsset = RateBNBwithUSD(); rateRepaymentAsset = getLatesPriceToUSD(repaymentAsset); } rateLoanAsset * 10**18, rateRepaymentAsset ); exchangeRate = xchange; }
12,600,078
[ 1, 2047, 4508, 2045, 287, 1758, 353, 1758, 12, 20, 3631, 866, 605, 20626, 7829, 4993, 598, 587, 9903, 4508, 2045, 287, 774, 3378, 40, 273, 261, 11890, 5034, 12, 4727, 15388, 38, 1918, 3378, 40, 10756, 225, 28183, 31183, 225, 3844, 13, 342, 261, 6625, 225, 23633, 1769, 971, 4508, 2045, 287, 1758, 353, 486, 605, 20626, 16, 336, 4891, 6205, 316, 587, 9903, 434, 4508, 2045, 287, 8170, 4508, 2045, 287, 774, 3378, 40, 273, 261, 11890, 5034, 12, 588, 48, 815, 5147, 774, 3378, 40, 12, 12910, 2045, 287, 1887, 3719, 282, 28183, 31183, 225, 3844, 13, 342, 261, 6625, 225, 23633, 1769, 336, 6205, 434, 605, 20626, 316, 587, 9903, 336, 6205, 316, 587, 9903, 434, 8170, 487, 28183, 3310, 336, 6205, 316, 587, 9903, 434, 605, 20626, 487, 2071, 2955, 3310, 336, 4891, 6205, 316, 587, 9903, 434, 8170, 487, 2071, 2955, 3310, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 445, 7029, 1504, 304, 6275, 1876, 11688, 4727, 12, 203, 3639, 1758, 4508, 2045, 287, 1887, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1758, 28183, 6672, 16, 203, 3639, 2254, 5034, 28183, 31183, 16, 203, 3639, 1758, 2071, 2955, 6672, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 28183, 6275, 16, 203, 5411, 2254, 5034, 7829, 4727, 16, 203, 5411, 2254, 5034, 4508, 2045, 287, 774, 3378, 40, 16, 203, 5411, 2254, 5034, 4993, 1504, 304, 6672, 16, 203, 5411, 2254, 5034, 4993, 426, 9261, 6672, 203, 3639, 262, 203, 565, 288, 203, 3639, 309, 261, 12910, 2045, 287, 1887, 422, 1758, 12, 20, 3719, 288, 203, 5411, 261, 16, 2254, 5034, 13489, 90, 6275, 13, 273, 14060, 10477, 10784, 429, 18, 698, 27860, 12, 203, 7734, 28183, 31183, 16, 203, 7734, 3844, 203, 5411, 11272, 203, 5411, 261, 16, 2254, 5034, 4508, 4727, 13, 273, 14060, 10477, 10784, 429, 18, 698, 27860, 12, 203, 7734, 13489, 90, 6275, 16, 203, 7734, 2254, 5034, 12, 4727, 15388, 38, 1918, 3378, 40, 10756, 203, 5411, 11272, 203, 5411, 261, 16, 2254, 5034, 4508, 774, 3378, 40, 13, 273, 14060, 10477, 10784, 429, 18, 698, 7244, 12, 203, 7734, 4508, 4727, 16, 203, 7734, 261, 6625, 380, 1728, 636, 25, 13, 203, 5411, 11272, 203, 203, 5411, 4508, 2045, 287, 774, 3378, 40, 273, 4508, 774, 3378, 40, 31, 203, 5411, 261, 16, 2254, 5034, 13489, 90, 6275, 13, 273, 14060, 10477, 10784, 429, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@lbertenasco/contract-utils/contracts/utils/UtilsReady.sol"; import "../sugar-mommy/Keep3rJob.sol"; import "../../interfaces/keep3r/IVaultKeep3rJob.sol"; import "../../interfaces/yearn/IEarnableVault.sol"; contract VaultKeep3rJob is UtilsReady, Keep3rJob, IVaultKeep3rJob { using SafeMath for uint256; mapping(address => uint256) public requiredEarn; mapping(address => uint256) public lastEarnAt; uint256 public earnCooldown; EnumerableSet.AddressSet internal _availableVaults; constructor(address _keep3rSugarMommy, uint256 _earnCooldown) public UtilsReady() Keep3rJob(_keep3rSugarMommy) { _setEarnCooldown(_earnCooldown); } function isVaultKeep3rJob() external pure override returns (bool) { return true; } // Setters function addVaults(address[] calldata _vaults, uint256[] calldata _requiredEarns) external override onlyGovernor { require(_vaults.length == _requiredEarns.length, "vault-keep3r::add-vaults:vaults-required-earns-different-length"); for (uint256 i; i < _vaults.length; i++) { _addVault(_vaults[i], _requiredEarns[i]); } } function addVault(address _vault, uint256 _requiredEarn) external override onlyGovernor { _addVault(_vault, _requiredEarn); } function _addVault(address _vault, uint256 _requiredEarn) internal { require(requiredEarn[_vault] == 0, "vault-keep3r::add-vault:vault-already-added"); _setRequiredEarn(_vault, _requiredEarn); _availableVaults.add(_vault); emit VaultAdded(_vault, _requiredEarn); } function updateRequiredEarnAmount(address _vault, uint256 _requiredEarn) external override onlyGovernor { require(requiredEarn[_vault] > 0, "vault-keep3r::update-required-earn:vault-not-added"); _setRequiredEarn(_vault, _requiredEarn); emit VaultModified(_vault, _requiredEarn); } function removeVault(address _vault) external override onlyGovernor { require(requiredEarn[_vault] > 0, "vault-keep3r::remove-vault:vault-not-added"); requiredEarn[_vault] = 0; _availableVaults.remove(_vault); emit VaultRemoved(_vault); } function _setRequiredEarn(address _vault, uint256 _requiredEarn) internal { require(_requiredEarn > 0, "vault-keep3r::set-required-earn:should-not-be-zero"); requiredEarn[_vault] = _requiredEarn; } function setEarnCooldown(uint256 _earnCooldown) external override onlyGovernor { _setEarnCooldown(_earnCooldown); } function _setEarnCooldown(uint256 _earnCooldown) internal { require(_earnCooldown > 0, "vault-keep3r::set-earn-cooldown:should-not-be-zero"); earnCooldown = _earnCooldown; } // Getters function vaults() public view override returns (address[] memory _vaults) { _vaults = new address[](_availableVaults.length()); for (uint256 i; i < _availableVaults.length(); i++) { _vaults[i] = _availableVaults.at(i); } } function calculateEarn(address _vault) public view override returns (uint256 _amount) { require(requiredEarn[_vault] > 0, "vault-keep3r::calculate-earn:vault-not-added"); return IEarnableVault(_vault).available(); } function workable(address _vault) public view override returns (bool) { require(requiredEarn[_vault] > 0, "vault-keep3r::workable:vault-not-added"); return (calculateEarn(_vault) >= requiredEarn[_vault] && block.timestamp > lastEarnAt[_vault].add(earnCooldown)); } // Keep3r actions function work(address _vault) external override { require(workable(_vault), "vault-keep3r::earn:not-workable"); _startJob(msg.sender); _earn(_vault); _endJob(msg.sender); emit EarnByKeeper(_vault); } // Governor keeper bypass function forceWork(address _vault) external override onlyGovernor { _earn(_vault); emit EarnByGovernor(_vault); } function _earn(address _vault) internal { IEarnableVault(_vault).earn(); lastEarnAt[_vault] = block.timestamp; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; import './Governable.sol'; import './CollectableDust.sol'; import './Pausable.sol'; import './Migratable.sol'; abstract contract UtilsReady is Governable, CollectableDust, Pausable, Migratable { constructor() public Governable(msg.sender) { } // Governable: restricted-access function setPendingGovernor(address _pendingGovernor) external override onlyGovernor { _setPendingGovernor(_pendingGovernor); } function acceptGovernor() external override onlyPendingGovernor { _acceptGovernor(); } // Collectable Dust: restricted-access function sendDust( address _to, address _token, uint256 _amount ) external override virtual onlyGovernor { _sendDust(_to, _token, _amount); } // Pausable: restricted-access function pause(bool _paused) external override onlyGovernor { _pause(_paused); } // Migratable: restricted-access function migrate(address _to) external onlyGovernor { _migrated(_to); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@lbertenasco/contract-utils/contracts/utils/UtilsReady.sol"; import "../../interfaces/sugar-mommy/IKeep3rSugarMommy.sol"; import "../../interfaces/sugar-mommy/IKeep3rJob.sol"; abstract contract Keep3rJob is IKeep3rJob { using SafeMath for uint256; IKeep3rSugarMommy public Keep3rSugarMommy; constructor(address _keep3rSugarMommy) public { Keep3rSugarMommy = IKeep3rSugarMommy(_keep3rSugarMommy); } function isKeep3rJob() external pure override returns (bool) { return true; } // Keep3rSugarMommy actions function _startJob(address _keeper) internal { Keep3rSugarMommy.start(_keeper); } function _endJob(address _keeper) internal { Keep3rSugarMommy.end(_keeper, address(0), 0); } function _endJob(address _keeper, uint256 _amount) internal { Keep3rSugarMommy.end(_keeper, address(0), _amount); } function _endJob( address _keeper, address _credit, uint256 _amount ) internal { Keep3rSugarMommy.end(_keeper, _credit, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVaultKeep3rJob { event VaultAdded(address _vault, uint256 _requiredEarn); event VaultModified(address _vault, uint256 _requiredEarn); event VaultRemoved(address _vault); function isVaultKeep3rJob() external pure returns (bool); // Actions by Keeper event EarnByKeeper(address _vault); // Actions forced by governance event EarnByGovernor(address _vault); // Keep3r actions function workable(address _vault) external view returns (bool); function work(address _vault) external; // Governance Keeper bypass function forceWork(address _vault) external; // Setters function addVaults(address[] calldata _vaults, uint256[] calldata _requiredEarns) external; function addVault(address _vault, uint256 _requiredEarn) external; function updateRequiredEarnAmount(address _vault, uint256 _requiredEarn) external; function removeVault(address _vault) external; function setEarnCooldown(uint256 _earnCooldown) external; // Getters function vaults() external view returns (address[] memory _vaults); function calculateEarn(address _vault) external view returns (uint256 _amount); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IEarnableVault { function earn() external; function available() external view returns (uint256 _available); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; import '../../interfaces/utils/IGovernable.sol'; abstract contract Governable is IGovernable { address public governor; address public pendingGovernor; constructor(address _governor) public { require(_governor != address(0), 'governable/governor-should-not-be-zero-address'); governor = _governor; } function _setPendingGovernor(address _pendingGovernor) internal { require(_pendingGovernor != address(0), 'governable/pending-governor-should-not-be-zero-addres'); pendingGovernor = _pendingGovernor; emit PendingGovernorSet(_pendingGovernor); } function _acceptGovernor() internal { governor = pendingGovernor; pendingGovernor = address(0); emit GovernorAccepted(); } modifier onlyGovernor { require(msg.sender == governor, 'governable/only-governor'); _; } modifier onlyPendingGovernor { require(msg.sender == pendingGovernor, 'governable/only-pending-governor'); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/EnumerableSet.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import '../../interfaces/utils/ICollectableDust.sol'; abstract contract CollectableDust is ICollectableDust { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; EnumerableSet.AddressSet internal protocolTokens; constructor() public {} function _addProtocolToken(address _token) internal { require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol'); protocolTokens.add(_token); } function _removeProtocolToken(address _token) internal { require(protocolTokens.contains(_token), 'collectable-dust/token-not-part-of-the-protocol'); protocolTokens.remove(_token); } function _sendDust( address _to, address _token, uint256 _amount ) internal { require(_to != address(0), 'collectable-dust/cant-send-dust-to-zero-address'); require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol'); if (_token == ETH_ADDRESS) { payable(_to).transfer(_amount); } else { IERC20(_token).safeTransfer(_to, _amount); } emit DustSent(_to, _token, _amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; import '../../interfaces/utils/IPausable.sol'; abstract contract Pausable is IPausable { bool public paused; constructor() public {} modifier notPaused() { require(!paused, 'paused'); _; } function _pause(bool _paused) internal { require(paused != _paused, 'no-change'); paused = _paused; emit Paused(_paused); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; import '../../interfaces/utils/IMigratable.sol'; abstract contract Migratable is IMigratable { address public override migratedTo; constructor() public {} modifier notMigrated() { require(migratedTo == address(0), 'migrated'); _; } function _migrated(address _to) internal { require(migratedTo == address(0), 'already-migrated'); require(_to != address(0), 'migrate-to-address-0'); migratedTo = _to; emit Migrated(_to); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; interface IGovernable { event PendingGovernorSet(address pendingGovernor); event GovernorAccepted(); function setPendingGovernor(address _pendingGovernor) external; function acceptGovernor() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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(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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; interface ICollectableDust { event DustSent(address _to, address token, uint256 amount); function sendDust(address _to, address _token, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; interface IPausable { event Paused(bool _paused); function pause(bool _paused) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.8; interface IMigratable { event Migrated(address _to); function migratedTo() external view returns (address _to); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IKeep3rSugarMommy { event Keep3rSet(address _keep3r); event Keep3rRequirementsSet(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA); event JobStarted(address _job, address _keeper); event JobEnded(address _job, address _keeper); function isKeep3rSugarMommy() external pure returns (bool); function setKeep3r(address _keep3r) external; function setKeep3rRequirements( address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA ) external; function jobs() external view returns (address[] memory validJobs); function start(address _keeper) external; function end( address _keeper, address _credit, uint256 _amount ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IKeep3rJob { function isKeep3rJob() external pure returns (bool); // Mock functions // function workable() external view returns (bool); // function work() external; // function forceWork() external; }
Governor keeper bypass
function forceWork(address _vault) external override onlyGovernor { _earn(_vault); emit EarnByGovernor(_vault); }
271,541
[ 1, 43, 1643, 29561, 417, 9868, 17587, 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, 2944, 2421, 12, 2867, 389, 26983, 13, 3903, 3849, 1338, 43, 1643, 29561, 288, 203, 3639, 389, 73, 1303, 24899, 26983, 1769, 203, 3639, 3626, 512, 1303, 858, 43, 1643, 29561, 24899, 26983, 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, -100, -100, -100 ]
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public tokenTotalSupply; function balanceOf(address who) constant returns(uint256); function allowance(address owner, address spender) constant returns(uint256); function transfer(address to, uint256 value) returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); function transferFrom(address from, address to, uint256 value) returns (bool success); function approve(address spender, uint256 value) returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() constant returns (uint256 availableSupply); } /** * @title Standard ERC20 token * * @dev Implemantation of the basic standart token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract BioToken is ERC20, Ownable { using SafeMath for uint; string public name = "BIONT Token"; string public symbol = "BIONT"; uint public decimals = 18; bool public tradingStarted = false; bool public mintingFinished = false; bool public salePaused = false; uint256 public tokenTotalSupply = 0; uint256 public trashedTokens = 0; uint256 public hardcap = 140000000 * (10 ** decimals); // 140 million tokens uint256 public ownerTokens = 14000000 * (10 ** decimals); // 14 million tokens uint public ethToToken = 300; // 1 eth buys 300 tokens uint public noContributors = 0; uint public start = 1503346080; // 08/21/2017 @ 20:08pm (UTC) uint public initialSaleEndDate = start + 9 weeks; uint public ownerGrace = initialSaleEndDate + 182 days; uint public fiveYearGrace = initialSaleEndDate + 5 * 365 days; address public multisigVault; address public lockedVault; address public ownerVault; address public authorizerOne; address public authorizerTwo; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(address => uint256) authorizedWithdrawal; event Mint(address indexed to, uint256 value); event MintFinished(); event TokenSold(address recipient, uint256 ether_amount, uint256 pay_amount, uint256 exchangerate); event MainSaleClosed(); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } modifier canMint() { if (mintingFinished) { revert(); } _; } /** * @dev modifier that throws if trading has not started yet */ modifier hasStartedTrading() { require(tradingStarted); _; } /** * @dev modifier to allow token creation only when the sale IS ON */ modifier saleIsOn() { require(now > start && now < initialSaleEndDate && salePaused == false); _; } /** * @dev modifier to allow token creation only when the hardcap has not been reached */ modifier isUnderHardCap() { require(tokenTotalSupply <= hardcap); _; } function BioToken(address _ownerVault, address _authorizerOne, address _authorizerTwo, address _lockedVault, address _multisigVault) { ownerVault = _ownerVault; authorizerOne = _authorizerOne; authorizerTwo = _authorizerTwo; lockedVault = _lockedVault; multisigVault = _multisigVault; mint(ownerVault, ownerTokens); } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) private canMint returns(bool) { tokenTotalSupply = tokenTotalSupply.add(_amount); require(tokenTotalSupply <= hardcap); balances[_to] = balances[_to].add(_amount); noContributors = noContributors.add(1); Mint(_to, _amount); Transfer(this, _to, _amount); return true; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function masterMint(address _to, uint256 _amount) public canMint onlyOwner returns(bool) { tokenTotalSupply = tokenTotalSupply.add(_amount); require(tokenTotalSupply <= hardcap); balances[_to] = balances[_to].add(_amount); noContributors = noContributors.add(1); Mint(_to, _amount); Transfer(this, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() private onlyOwner returns(bool) { mintingFinished = true; MintFinished(); return true; } /** * @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) onlyPayloadSize(2 * 32) hasStartedTrading returns (bool success) { // don't allow the vault to make transfers if (msg.sender == lockedVault && now < fiveYearGrace) { revert(); } // owner needs to wait as well if (msg.sender == ownerVault && now < ownerGrace) { revert(); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) hasStartedTrading returns (bool success) { if (_from == lockedVault && now < fiveYearGrace) { revert(); } // owner needs to wait as well if (_from == ownerVault && now < ownerGrace) { revert(); } var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Transfer tokens from one address to another according to off exchange agreements * @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 masterTransferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public hasStartedTrading onlyOwner returns (bool success) { if (_from == lockedVault && now < fiveYearGrace) { revert(); } // owner needs to wait as well if (_from == ownerVault && now < ownerGrace) { revert(); } balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); Transfer(_from, _to, _value); return true; } function totalSupply() constant returns (uint256 availableSupply) { return tokenTotalSupply; } /** * @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) constant returns(uint256 balance) { return balances[_owner]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool success) { // 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 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens than 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) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function startTrading() onlyOwner { tradingStarted = true; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function pauseSale() onlyOwner { salePaused = true; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function resumeSale() onlyOwner { salePaused = false; } /** * @dev Allows the owner to enable the trading. This can not be undone */ function getNoContributors() constant returns(uint contributors) { return noContributors; } /** * @dev Allows the owner to set the multisig wallet address. * @param _multisigVault the multisig wallet address */ function setMultisigVault(address _multisigVault) public onlyOwner { if (_multisigVault != address(0)) { multisigVault = _multisigVault; } } function setAuthorizedWithdrawalAmount(uint256 _amount) public { if (_amount < 0) { revert(); } if (msg.sender != authorizerOne && msg.sender != authorizerTwo) { revert(); } authorizedWithdrawal[msg.sender] = _amount; } /** * @dev Allows the owner to send the funds to the vault. * @param _amount the amount in wei to send */ function withdrawEthereum(uint256 _amount) public onlyOwner { require(multisigVault != address(0)); require(_amount <= this.balance); // wei if (authorizedWithdrawal[authorizerOne] != authorizedWithdrawal[authorizerTwo]) { revert(); } if (_amount > authorizedWithdrawal[authorizerOne]) { revert(); } if (!multisigVault.send(_amount)) { revert(); } authorizedWithdrawal[authorizerOne] = authorizedWithdrawal[authorizerOne].sub(_amount); authorizedWithdrawal[authorizerTwo] = authorizedWithdrawal[authorizerTwo].sub(_amount); } function showAuthorizerOneAmount() constant public returns(uint256 remaining) { return authorizedWithdrawal[authorizerOne]; } function showAuthorizerTwoAmount() constant public returns(uint256 remaining) { return authorizedWithdrawal[authorizerTwo]; } function showEthBalance() constant public returns(uint256 remaining) { return this.balance; } function retrieveTokens() public onlyOwner { require(lockedVault != address(0)); uint256 capOut = hardcap.sub(tokenTotalSupply); tokenTotalSupply = hardcap; balances[lockedVault] = balances[lockedVault].add(capOut); Transfer(this, lockedVault, capOut); } function trashTokens(address _from, uint256 _amount) onlyOwner returns(bool) { balances[_from] = balances[_from].sub(_amount); trashedTokens = trashedTokens.add(_amount); tokenTotalSupply = tokenTotalSupply.sub(_amount); } function decreaseSupply(uint256 value, address from) onlyOwner returns (bool) { balances[from] = balances[from].sub(value); trashedTokens = trashedTokens.add(value); tokenTotalSupply = tokenTotalSupply.sub(value); Transfer(from, 0, value); return true; } function finishSale() public onlyOwner { finishMinting(); retrieveTokens(); startTrading(); MainSaleClosed(); } function saleOn() constant returns(bool) { return (now > start && now < initialSaleEndDate && salePaused == false); } /** * @dev Allows anyone to create tokens by depositing ether. * @param recipient the recipient to receive tokens. */ function createTokens(address recipient) public isUnderHardCap saleIsOn payable { uint bonus = 0; uint period = 1 weeks; uint256 tokens; if (now <= start + 2 * period) { bonus = 20; } else if (now > start + 2 * period && now <= start + 3 * period) { bonus = 15; } else if (now > start + 3 * period && now <= start + 4 * period) { bonus = 10; } else if (now > start + 4 * period && now <= start + 5 * period) { bonus = 5; } // the bonus is in percentages, solidity is doing standard integer division, basically rounding 'down' if (bonus > 0) { tokens = ethToToken.mul(msg.value) + ethToToken.mul(msg.value).mul(bonus).div(100); } else { tokens = ethToToken.mul(msg.value); } if (tokens <= 0) { revert(); } mint(recipient, tokens); TokenSold(recipient, msg.value, tokens, ethToToken); } function() external payable { createTokens(msg.sender); } }
* @title ERC20 interface/
contract ERC20 { uint256 public tokenTotalSupply; function balanceOf(address who) constant returns(uint256); function allowance(address owner, address spender) constant returns(uint256); function transfer(address to, uint256 value) returns (bool success); event Transfer(address indexed from, address indexed to, uint256 value); function transferFrom(address from, address to, uint256 value) returns (bool success); function approve(address spender, uint256 value) returns (bool success); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() constant returns (uint256 availableSupply); }
1,756,185
[ 1, 654, 39, 3462, 1560, 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, 16351, 4232, 39, 3462, 288, 203, 565, 2254, 5034, 1071, 1147, 5269, 3088, 1283, 31, 203, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 5381, 1135, 12, 11890, 5034, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 5381, 1135, 12, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 1135, 261, 6430, 2216, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 1135, 261, 6430, 2216, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 5381, 1135, 261, 11890, 5034, 2319, 3088, 1283, 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 ]
./full_match/1/0x08e46853c6a3b57D01F1748041999fb8EB8fF9e5/sources/contracts/fundraising/libraries/LibAppStorage.sol
@dev Get equity badge. @return Equity badge contract instance return
function getBadge() internal view returns (IEquityBadge) { return appStorage().equityBadge; }
17,012,051
[ 1, 967, 1298, 560, 15654, 18, 327, 19008, 560, 15654, 6835, 791, 327, 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, 565, 445, 2882, 361, 908, 1435, 2713, 1476, 1135, 261, 8732, 372, 560, 6434, 908, 13, 288, 203, 3639, 327, 595, 3245, 7675, 14298, 560, 6434, 908, 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 ]
/* || THE LEXDAO REGISTRY (TLDR) || 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~ */ pragma solidity 0.5.9; /*************** OPENZEPPELIN REFERENCE CONTRACTS - SafeMath, ScribeRole, ERC-20 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 addScribe(address account) public onlyScribe { _addScribe(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); } /*************** TLDR CONTRACT ***************/ contract lexDAORegistry is ScribeRole { // **TLDR: lexDAO-maintained legal engineering registry to wrap and enforce digital transactions with legal and ethereal security** using SafeMath for uint256; // **lexAgon DAO treasury references (aragon.org digital organization)** address payable public lexAgonDAO = 0xBBE222Ef97076b786f661246232E41BE0DFf6cc4; // **counters for lexScribe lexScriptWrapper and registered DDR** uint256 public LSW = 1; // **number of lexScriptWrappers enscribed herein** uint256 public RDDR; // **number of DDRs registered hereby** // **internal lexScript references** // uint256 private lexRate; // **rate paid from payDDR transaction to associated lexAddress (lexFee)** address private lexAddress; // **lexScribe nominated lexAddress to receive lexFee** mapping(address => uint256) public reputation; // **mapping lexScribe reputation** mapping(address => uint256) public lastActionTimestamp; // **mapping lexScribe governance actions* mapping (uint256 => lexScriptWrapper) public lexScript; // **mapping registered lexScript 'wet code' templates** mapping (uint256 => DDR) public rddr; // **mapping registered rddr call numbers** struct lexScriptWrapper { // **LSW: Digital Dollar Retainer (DDR) lexScript templates maintained by lexDAO scribes (lexScribe)** address lexScribe; // **lexScribe that enscribed lexScript template into TLDR** address lexAddress; // **ethereum address to forward lexScript template lexScribe fees** string templateTerms; // **lexScript template terms to wrap DDR for legal security** uint256 lexID; // **ID number to reference in DDR to inherit lexScript wrapper** uint256 lexRate; // **lexScribe fee in ddrToken type per rddr payment made thereunder / e.g., 100 = 1% fee on rddr payDDR payment transaction** } struct DDR { // **Digital Dollar Retainer** address client; // **client ethereum address** address provider; // **ethereum address that receives payments in exchange for goods or services** IERC20 ddrToken; // **ERC-20 digital token address used to transfer value on ethereum under rddr / e.g., DAI 'digital dollar' - 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359** string deliverable; // **goods or services (deliverable) retained for benefit of ethereum payments** string governingLawForum; // **choice of law and forum for retainer relationship (or similar legal description)** uint256 ddrNumber; // **rddr number generated on registration / identifies rddr for payDDR calls** uint256 timeStamp; // **block.timestamp of registration used to calculate retainerTermination UnixTime** uint256 retainerDuration; // **duration of rddr in seconds** uint256 retainerTermination; // **termination date of rddr in UnixTime** uint256 deliverableRate; // **rate for rddr deliverables in digital dollar wei amount / 1 = 1000000000000000000** uint256 paid; // **tracking amount of designated ERC-20 paid under rddr in wei amount** uint256 payCap; // **cap in wei amount to limit payments under rddr**; uint256 lexID; // **lexID number reference to include lexScriptWrapper for legal security / default '0' for general DDR lexScript template** } constructor() public { // **deploys TLDR contract and stores base template "0" (lexID) for rddr lexScript terms** address LEXScribe = msg.sender; // **TLDR creator is initial lexScribe** // **default lexScript legal wrapper stating general human-readable DDR terms for rddr to inherit / lexID = '0'** string memory ddrTerms = "|| Establishing a digital retainer hereby as [[ddrNumber]] and acknowledging mutual consideration and agreement, Client, identified by ethereum address 0x[[client]], commits to perform under this digital payment transactional script capped at $[[payCap]] digital dollar value denominated in 0x[[ddrToken]] for benefit of Provider, identified by ethereum address 0x[[provider]], in exchange for prompt satisfaction of the following, [[deliverable]], to Client by Provider upon scripted payments set at the rate of $[[deliverableRate]] per deliverable, with such retainer relationship not to exceed [[retainerDuration]] seconds and to be governed by choice of [[governingLawForum]] law and 'either/or' arbitration rules in [[governingLawForum]]. ||"; uint256 lexID = 0; // **default lexID for constructor / general rddr reference** uint256 LEXRate = 100; // **1% lexRate** address LEXAddress = 0xBBE222Ef97076b786f661246232E41BE0DFf6cc4; // **Open, ESQ LLC_DAO ethereum address** lexScript[lexID] = lexScriptWrapper( // **populate default '0' lexScript data for reference in LSW** LEXScribe, LEXAddress, ddrTerms, lexID, LEXRate); } // **TLDR Events** event Enscribed(uint256 indexed lexID, address indexed lexScribe); // **triggered on successful edits to LSW** event Registered(uint256 indexed ddrNumber, uint256 indexed lexID, address client, address provider); // **triggered on successful registration** event Paid(uint256 indexed ddrNumber, uint256 indexed lexID, uint256 ratePaid, uint256 totalPaid, address client); // **triggered on successful rddr payments** /*************** GOVERNANCE FUNCTIONS ***************/ // **lexScribes can stake ether (Ξ) value for TLDR reputation and function access** function stakeReputation() payable public onlyScribe { require(msg.value == 0.1 ether); reputation[msg.sender] = 10; address(lexAgonDAO).transfer(msg.value); } // **check on lexScribe reputation** function isReputable(address x) public view returns (bool) { return reputation[x] > 0; } // **restricts governance function calls to once per day** modifier cooldown() { require(now.sub(lastActionTimestamp[msg.sender]) > 1 days); _; lastActionTimestamp[msg.sender] = now; } // **reputable LexScribes can reduce each other's reputation** function reduceScribeRep(address reducedLexScribe) cooldown public { require(isReputable(msg.sender)); reputation[reducedLexScribe] = reputation[reducedLexScribe].sub(1); } // **reputable LexScribes can repair each other's reputation** function repairScribeRep(address repairedLexScribe) cooldown public { require(isReputable(msg.sender)); require(reputation[repairedLexScribe] < 10); reputation[repairedLexScribe] = reputation[repairedLexScribe].add(1); lastActionTimestamp[msg.sender] = now; } /*************** LEXSCRIBE FUNCTIONS ***************/ // **reputable lexScribes can register lexScript legal wrappers on TLDR and program fees for usage** function writeLEXScriptWrapper(string memory templateTerms, uint256 LEXRate, address LEXAddress) public onlyScribe { require(isReputable(msg.sender)); address lexScribe = msg.sender; uint256 lexID = LSW.add(1); // **reflects new lexScript value for tracking legal wrappers** LSW = LSW.add(1); // counts new entry to LSW lexScript[lexID] = lexScriptWrapper( // populate lexScript data for reference in rddr lexScribe, LEXAddress, templateTerms, lexID, LEXRate); emit Enscribed(lexID, lexScribe); } // **lexScribes can update registered lexScript legal wrappers with newTemplateTerms and newLexAddress** function editLEXScriptWrapper(uint256 lexID, string memory newTemplateTerms, address newLEXAddress) public { lexScriptWrapper storage lS = lexScript[lexID]; require(address(msg.sender) == lS.lexScribe); // program safety check / authorization lexScript[lexID] = lexScriptWrapper( // populate updated lexScript data for reference in rddr msg.sender, newLEXAddress, newTemplateTerms, lexID, lS.lexRate); emit Enscribed(lexID, msg.sender); } /*************** MARKET FUNCTIONS ***************/ // **register DDR with TLDR lexScripts** function registerDDR( address client, address provider, IERC20 ddrToken, string memory deliverable, string memory governingLawForum, uint256 retainerDuration, uint256 deliverableRate, uint256 payCap, uint256 lexID) public { require(deliverableRate <= payCap, "registerDDR: deliverableRate cannot exceed payCap"); // **program safety check / economics** uint256 ddrNumber = RDDR.add(1); // **reflects new rddr value for tracking payments** uint256 paid = 0; // **initial zero value for rddr** uint256 timeStamp = now; // **block.timestamp of rddr** uint256 retainerTermination = timeStamp + retainerDuration; // **rddr termination date in UnixTime** RDDR = RDDR.add(1); // counts new entry to RDDR rddr[ddrNumber] = DDR( // populate rddr data client, provider, ddrToken, deliverable, governingLawForum, ddrNumber, timeStamp, retainerDuration, retainerTermination, deliverableRate, paid, payCap, lexID); emit Registered(ddrNumber, lexID, client, provider); } // **pay registered DDR on TLDR** function payDDR(uint256 ddrNumber) public { // **forwards approved ddrToken deliverableRate amount to provider ethereum address** DDR storage ddr = rddr[ddrNumber]; // **retrieve rddr data** lexScriptWrapper storage lS = lexScript[ddr.lexID]; require (now <= ddr.retainerTermination); // **program safety check / time** require(address(msg.sender) == ddr.client); // program safety check / authorization require(ddr.paid.add(ddr.deliverableRate) <= ddr.payCap, "payDAI: payCap exceeded"); // **program safety check / economics** uint256 lexFee = ddr.deliverableRate.div(lS.lexRate); ddr.ddrToken.transferFrom(msg.sender, ddr.provider, ddr.deliverableRate); // **executes ERC-20 transfer** ddr.ddrToken.transferFrom(msg.sender, lS.lexAddress, lexFee); ddr.paid = ddr.paid.add(ddr.deliverableRate); // **tracks amount paid under rddr** emit Paid(ddr.ddrNumber, ddr.lexID, ddr.deliverableRate, ddr.paid, msg.sender); } }
deploys TLDR contract and stores base template "0" (lexID) for rddr lexScript terms
constructor() public {
6,485,615
[ 1, 15037, 383, 1900, 14418, 6331, 6835, 471, 9064, 1026, 1542, 315, 20, 6, 261, 4149, 734, 13, 364, 27777, 86, 5275, 3651, 6548, 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 ]
[ 1, 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 ]
[ 1, 202, 12316, 1435, 1071, 288, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-29 */ // SPDX-License-Identifier: MIT // File: contracts/IERC2981.sol pragma solidity >=0.7.0 <0.9.0; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 { /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/ERC2981.sol pragma solidity >=0.7.0 <0.9.0; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 contract ERC2981 is ERC165, IERC2981 { struct RoyaltyInfo { address recipient; uint24 amount; } RoyaltyInfo private _royalties; /// @dev Sets token royalties /// @param recipient recipient of the royalties /// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties(address recipient, uint256 value) internal { require(value <= 10000, "ERC2981Royalties: Too high"); _royalties = RoyaltyInfo(recipient, uint24(value)); } /// @inheritdoc IERC2981 function royaltyInfo(uint256, uint256 value) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (value * royalties.amount) / 10000; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: contracts/Contract.sol // @S4FE NFT COLLECTION // @Omark dev HTTPS://WWW.S4FE.ORG pragma solidity >=0.7.0 <0.9.0; contract S4FE is ERC721,ERC2981,Ownable,Pausable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.15 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmountPerTx = 10; // how many NFTs can be Minted in one transaction uint256 public mintNumberlimit = 1000; // where the Stage mint limit uint256 public minMintAmount = 1; // the minumum NFTs can be minted address public royaltyRecipient = 0xFd4435A700E63CCa6F975EEC1919c95ECD164630; uint256 public royaltiesPercentage = 1000; // 10% royalties address public batchAddress; bytes32 public MerkleRoot = 0xf57971f28fba0312e2a19ab59b1a3a0d4f0144abbdf488047e89a8a1f2411466; bool public MerkleTree = true; bool public publicSale = false; // you to let ppl minting the NFT or Not bool public preSale = false; bool public revealed = false; constructor() ERC721("S4FE NFT", "S4F") { setHiddenMetadataUri("ipfs://QmcY3HNAckbe2VF6ub4je2fMSUYGB8KoZRon1TqG5KBM47/hidden.json"); _setRoyalties(royaltyRecipient, royaltiesPercentage); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); require(supply.current() + _mintAmount <= mintNumberlimit, "Smart Contract reached the max mint"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(publicSale, "The contract is paused!"); // i should check this if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "insufficient funds"); } _mintLoop(msg.sender, _mintAmount); } function mintBatch(uint256 _mintAmount,address _receiver) external { require(msg.sender == batchAddress,"only for batch address"); _mintLoop(_receiver, _mintAmount); } function buyPresale(bytes32[] calldata signature,uint256 _mintAmount) external payable mintCompliance(_mintAmount){ require(preSale ,"Presale is not active"); require(_mintAmount >= minMintAmount , "Min spend per person is low"); require(msg.value >= cost * _mintAmount, "insufficient funds"); if(MerkleTree == true){ bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(signature,MerkleRoot,leaf),"Invalid signature"); } _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } //Pausable Fonctions function approve(address to, uint256 tokenId) public virtual override whenNotPaused { 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); } function setApprovalForAll(address operator, bool approved) public virtual override whenNotPaused { _setApprovalForAll(_msgSender(), operator, approved); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override whenNotPaused{ //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner not approved"); _transfer(from, to, tokenId); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } //pause Or unpause Selling function setSellingPaused() public onlyOwner { _pause(); } function setSellingUnpaused() public onlyOwner { _unpause(); } // Control Variable function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setRoyaltyRecipient(address _NewAdress) public onlyOwner{ royaltyRecipient = _NewAdress; } function setRoyaltiesPercentage(uint256 _percentage) public onlyOwner{ royaltiesPercentage = _percentage; } function setMintNumberLimit(uint256 _limit) public onlyOwner { mintNumberlimit = _limit; } function setMinMintAmount(uint256 _limit) public onlyOwner { minMintAmount = _limit; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { MerkleRoot = _merkleRoot; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPublicSale(bool _state) public onlyOwner { publicSale = _state; } function setPreSale(bool _state) public onlyOwner { preSale = _state; } function setMerkleTree(bool _state) public onlyOwner{ MerkleTree = _state; } function setNextStage(uint256 _cost,uint256 _stageNumberlimit,uint256 _minMintAmount) public onlyOwner { cost = _cost; mintNumberlimit = _stageNumberlimit; minMintAmount = _minMintAmount; } function withdraw() public onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } // batch adress contract function setBatchAddress(address _adress) public onlyOwner { batchAddress = _adress; } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
where the Stage mint limit
uint256 public mintNumberlimit = 1000;
15,429,679
[ 1, 6051, 326, 16531, 312, 474, 1800, 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, 2254, 5034, 1071, 312, 474, 1854, 3595, 273, 4336, 31, 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, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/ISettV3.sol"; import "interfaces/badger/ISettV4.sol"; import "interfaces/badger/IController.sol"; import "interfaces/cvx/ICvxLocker.sol"; import "interfaces/snapshot/IDelegateRegistry.sol"; import "interfaces/curve/ICurvePool.sol"; import "../BaseStrategy.sol"; contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant BADGER_TREE = 0x660802Fc641b154aBA66a62137e71f331B6d787A; address public constant SUSHI_ROUTER = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV3 public constant CVX_VAULT = ISettV3(0x53C8E199eb2Cb7c01543C137078a038937a68E40); ISettV4 public constant CVXCRV_VAULT = ISettV4(0x2B5455aac8d64C14786c3a29858E43b5945819C0); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); // Curve Pool to swap between cvxCRV and CRV ICurvePool public constant CURVE_POOL = ICurvePool(0x9D0464996170c6B9e75eED71c68B99dDEDf279e8); bool public withdrawalSafetyCheck = true; bool public harvestOnRebalance = true; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = true; bool public processLocksOnRebalance = true; event Debug(string name, uint256 value); // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeGovernance( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); event PerformanceFeeStrategist( address indexed destination, address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; IERC20Upgradeable(reward).safeApprove(address(CVXCRV_VAULT), type(uint256).max); /// @dev do one off approvals here // Sushi to swap CRV -> CVX // TODO: REMOVE IERC20Upgradeable(CRV).safeApprove(SUSHI_ROUTER, type(uint256).max); // Curve to swap cvxCRV -> CRV // TODO: REMOVE IERC20Upgradeable(reward).safeApprove(address(CURVE_POOL), type(uint256).max); // Permissions for Locker IERC20Upgradeable(CVX).safeApprove(address(LOCKER), type(uint256).max); IERC20Upgradeable(CVX).safeApprove( address(CVX_VAULT), type(uint256).max ); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) external { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) external { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) external { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) external { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) external { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// ===== View Functions ===== function getBoostPayment() public view returns(uint256){ uint256 maximumBoostPayment = LOCKER.maximumBoostPayment(); require(maximumBoostPayment < 1500, "over max payment"); //max 15% return maximumBoostPayment; } /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.0"; } /// @dev From CVX Token to Helper Vault Token function CVXToWant(uint256 cvx) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return cvx.mul(10**18).div(bCVXToCVX); } /// @dev From Helper Vault Token to CVX Token function wantToCVX(uint256 want) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return want.mul(bCVXToCVX).div(10**18); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg } // Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals // then multiply it by the price per share as we need to convert CVX to bCVX uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; protectedTokens[3] = CVX; return protectedTokens; } /// ===== Permissioned Actions: Governance ===== /// @notice Delete if you don't need! function setKeepReward(uint256 _setKeepReward) external { _onlyGovernance(); } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // We receive bCVX -> Convert to CVX CVX_VAULT.withdraw(_amount); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), toDeposit, getBoostPayment()); } /// @dev utility function to convert all we can to bCVX /// @notice You may want to harvest before calling this to maximize the amount of bCVX you'll have function prepareWithdrawAll() external { _onlyGovernance(); LOCKER.processExpiredLocks(false); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only bCVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock and have to manually rebalance out of it" ); // NO-OP because you can't deposit AND transfer with bCVX // See prepareWithdrawAll above } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = IERC20Upgradeable(want).balanceOf(address(this)); if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (max < _amount) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256) { _onlyAuthorizedActors(); uint256 _beforeReward = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeReward); uint256 cvxCrvToGovernance = earnedReward.mul(performanceFeeGovernance).div(MAX_FEE); if(cvxCrvToGovernance > 0){ CVXCRV_VAULT.depositFor(IController(controller).rewards(), cvxCrvToGovernance); emit PerformanceFeeGovernance(IController(controller).rewards(), address(CVXCRV_VAULT), cvxCrvToGovernance, block.number, block.timestamp); } uint256 cvxCrvToStrategist = earnedReward.mul(performanceFeeStrategist).div(MAX_FEE); if(cvxCrvToStrategist > 0){ CVXCRV_VAULT.depositFor(strategist, cvxCrvToStrategist); emit PerformanceFeeStrategist(strategist, address(CVXCRV_VAULT), cvxCrvToStrategist, block.number, block.timestamp); } // Send rest of earned to tree //We send all rest to avoid dust and avoid protecting the token uint256 cvxCrvToTree = IERC20Upgradeable(reward).balanceOf(address(this)); CVXCRV_VAULT.depositFor(BADGER_TREE, cvxCrvToTree); emit TreeDistribution(address(CVXCRV_VAULT), cvxCrvToTree, block.number, block.timestamp); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earnedReward, block.number); /// @dev Harvest must return the amount of want increased return earnedReward; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { revert("no op"); // NOTE: For now tend is replaced by manualRebalance } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Redeposit into veCVX LOCKER.lock(address(this), toDeposit, getBoostPayment()); return toDeposit; } /// @dev process all locks, to redeem function manualProcessExpiredLocks() external whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat // Processed in the next harvest or during prepareMigrateAll } /// @dev Take all CVX and deposits in the CVX_VAULT function manualDepositCVXIntoVault() external whenNotPaused { _onlyGovernance(); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev Send all available bCVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendbCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 bCvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(bCvxAmount); } /// @dev use the currently available CVX to either lock or add to bCVX /// @notice toLock = 0, lock nothing, deposit in bCVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // CVX uninvested we got from harvest and unlocks uint256 balanceOfCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfCVX.add(balanceInLock).add(wantToCVX(balanceOfWant)); // Amount we want to have in lock uint256 newLockAmount = totalCVXBalance.mul(toLock).div(MAX_BPS); // We can't unlock enough, just deposit rest into bCVX if (newLockAmount <= balanceInLock) { // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } return; } // If we're continuing, then we are going to lock something (unless it's zero) uint256 cvxToLock = newLockAmount.sub(balanceInLock); // NOTE: We only lock the CVX we have and not the bCVX // bCVX should be sent back to vault and then go through earn // We do this because bCVX has "blockLock" and we can't both deposit and withdraw on the same block uint256 maxCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, getBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, getBoostPayment()); } // If anything else is left, deposit into vault uint256 cvxLeft = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxLeft > 0) { CVX_VAULT.deposit(cvxLeft); } // At the end of the rebalance, there won't be any balanceOfCVX as that token is not considered by our strat } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; interface ISettV3 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; pragma experimental ABIEncoderV2; interface ISettV4 { function deposit(uint256 _amount) external; function depositFor(address _recipient, uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICvxLocker { function maximumBoostPayment() external view returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface ICurvePool { function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "interfaces/uniswap/IUniswapRouterV2.sol"; import "interfaces/badger/IController.sol"; import "interfaces/badger/IStrategy.sol"; import "../SettAccessControl.sol"; /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController"); } function _onlyAuthorizedPausers() internal view { require(msg.sender == guardian || msg.sender == governance, "onlyPausers"); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public virtual view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public virtual view returns (bool) { return false; } function isProtectedToken(address token) public view returns (bool) { address[] memory protectedTokens = getProtectedTokens(); for (uint256 i = 0; i < protectedTokens.length; i++) { if (token == protectedTokens[i]) { return true; } } return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee"); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee"); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee"); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold"); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _want) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() public virtual view returns (address[] memory) { return new address[](0); } /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external virtual pure returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public virtual view returns (uint256); uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; interface IStrategy { function want() external view returns (address); function deposit() external; // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address) external returns (uint256 balance); // Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; // Controller | Vault role - withdraw should always return to Vault function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function getName() external pure returns (string memory); function setStrategist(address _strategist) external; function setWithdrawalFee(uint256 _withdrawalFee) external; function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external; function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external; function setGovernance(address _governance) external; function setController(address _controller) external; function tend() external; function harvest() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.11; import "../../deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist"); } function _onlyAuthorizedActors() internal view { require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors"); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
===== Permissioned Actions: Governance ===== @notice Delete if you don't need!
function setKeepReward(uint256 _setKeepReward) external { _onlyGovernance(); }
1,604,837
[ 1, 894, 33, 8509, 329, 18765, 30, 611, 1643, 82, 1359, 422, 12275, 225, 2504, 309, 1846, 2727, 1404, 1608, 5, 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, 444, 11523, 17631, 1060, 12, 11890, 5034, 389, 542, 11523, 17631, 1060, 13, 3903, 288, 203, 3639, 389, 3700, 43, 1643, 82, 1359, 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 ]
// SPDX-License-Identifier: Unlicense pragma solidity >=0.7.6; import './ERC20BaseToken.sol'; import './VERCHelper.sol'; /// @notice This contract implements deteministic ERC-20 deployements. Used for Habitat V(irtual) ERC-20. contract VirtualERC20Factory is ERC20BaseToken, VERCHelper { event Erc20Created(address indexed proxy); bool _initialized; /// @notice Returns the metadata of this (MetaProxy) contract. /// Only relevant with contracts created via the MetaProxy. /// @dev This function is aimed to be invoked with- & without a call. function getMetadata () public pure returns ( string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply, bytes32 _domainSeparator ) { assembly { function stringcopy (_calldataPtr) -> calldataPtr, memPtr { calldataPtr := _calldataPtr let paddedLen := add( // len of bytes 32, // roundup mul( div( add(calldataload(calldataPtr), 31), 32 ), 32 ) ) memPtr := mload(64) mstore(64, add(memPtr, paddedLen)) calldatacopy(memPtr, calldataPtr, paddedLen) calldataPtr := add(calldataPtr, paddedLen) } // calldata layout: // [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ] let sizeOfPos := sub(calldatasize(), 32) let calldataPtr := sub(sizeOfPos, calldataload(sizeOfPos)) // skip the first 64 bytes (abi encoded stuff) calldataPtr := add(calldataPtr, 64) _decimals := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) _totalSupply := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) _domainSeparator := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) // copy token name to memory calldataPtr, _name := stringcopy(calldataPtr) // copy token symbol to memory calldataPtr, _symbol := stringcopy(calldataPtr) } } /// @notice VERC MetaProxy construction via calldata. function createProxy ( string memory _name, string memory _symbol, uint8 _decimals, uint256 _totalSupply, bytes32 _domainSeparator ) external returns (address addr) { // create the proxy first addr = _metaProxyFromCalldata(); require(addr != address(0), 'CP1'); emit Erc20Created(addr); bytes32 tokenNameHash = keccak256(bytes(_name)); bytes32 ret; assembly { // load free memory ptr let ptr := mload(64) // keep a copy to calculate the length later let start := ptr // we can't include `address verifyingContract` // keccak256('EIP712Domain(string name,uint256 chainId)') mstore(ptr, 0xcc85e4a69ca54da41cc4383bb845cbd1e15ef8a13557a6bed09b8bea2a0d92ff) ptr := add(ptr, 32) // see tokenNameHash mstore(ptr, tokenNameHash) ptr := add(ptr, 32) // store chainid mstore(ptr, chainid()) ptr := add(ptr, 32) // hash ret := keccak256(start, sub(ptr, start)) } // verify DOMAIN_SEPARATOR require(ret == _domainSeparator, 'CP2'); VirtualERC20Factory(addr).init(_INITIAL_OWNER()); } /// @notice Based on EIP-3448 /// @dev Creates a child with metadata from calldata. /// Copies everything from calldata except the first 4 bytes. /// @return addr address(0) on error, else the address of the new contract (proxy) function _metaProxyFromCalldata () internal returns (address addr) { uint256 metadataSize; assembly { metadataSize := sub(calldatasize(), 4) } bytes memory initCode = VERCHelper._getInitCodeForVERC(address(this), 4, metadataSize); assembly { let start := add(initCode, 32) let size := mload(initCode) addr := create2(0, start, size, 0) } } /// @dev The address who receives the `totalSupply` on `init`. function _INITIAL_OWNER () internal view virtual returns (address) { } /// @notice Initializes and mints the total supply to the `_initialOwner`. function init (address _initialOwner) external { require(_initialized == false, 'S1'); _initialized = true; (,,,uint256 _totalSupply,) = getMetadata(); _balances[_initialOwner] = _totalSupply; emit Transfer(address(0), _initialOwner, _totalSupply); } /// @notice Returns the name of token. function name () public virtual view returns (string memory) { (string memory _name,,,,) = getMetadata(); return _name; } /// @notice Returns the symbol of the token. function symbol () public virtual view returns (string memory) { (,string memory _symbol,,,) = getMetadata(); return _symbol; } /// @notice Returns the decimal place of the token. function decimals () public virtual view returns (uint8) { (,,uint8 _decimals,,) = getMetadata(); return _decimals; } /// @notice Returns the DOMAIN_SEPARATOR. See EIP-2612. function DOMAIN_SEPARATOR () public virtual override view returns (bytes32) { (,,,,bytes32 _domainSeparator) = getMetadata(); return _domainSeparator; } /// @notice Returns the total supply of this token. function totalSupply () public virtual view returns (uint256) { (,,,uint256 _totalSupply,) = getMetadata(); return _totalSupply; } }
@notice Returns the metadata of this (MetaProxy) contract. Only relevant with contracts created via the MetaProxy. @dev This function is aimed to be invoked with- & without a call. len of bytes roundup
) { assembly { function stringcopy (_calldataPtr) -> calldataPtr, memPtr { calldataPtr := _calldataPtr let paddedLen := add( 32, mul( div( add(calldataload(calldataPtr), 31), 32 ), 32 ) ) memPtr := mload(64) mstore(64, add(memPtr, paddedLen)) calldatacopy(memPtr, calldataPtr, paddedLen) calldataPtr := add(calldataPtr, paddedLen) } let calldataPtr := sub(sizeOfPos, calldataload(sizeOfPos)) _decimals := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) _totalSupply := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) _domainSeparator := calldataload(calldataPtr) calldataPtr := add(calldataPtr, 32) } }
5,459,156
[ 1, 1356, 326, 1982, 434, 333, 261, 2781, 3886, 13, 6835, 18, 5098, 9368, 598, 20092, 2522, 3970, 326, 6565, 3886, 18, 225, 1220, 445, 353, 279, 381, 329, 358, 506, 8187, 598, 17, 473, 2887, 279, 745, 18, 562, 434, 1731, 3643, 416, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 262, 288, 203, 565, 19931, 288, 203, 1377, 445, 533, 3530, 261, 67, 1991, 892, 5263, 13, 317, 745, 892, 5263, 16, 1663, 5263, 288, 203, 3639, 745, 892, 5263, 519, 389, 1991, 892, 5263, 203, 203, 3639, 2231, 14426, 2891, 519, 527, 12, 203, 1850, 3847, 16, 203, 1850, 14064, 12, 203, 5411, 3739, 12, 203, 2868, 527, 12, 1991, 72, 3145, 6189, 12, 1991, 892, 5263, 3631, 8231, 3631, 203, 2868, 3847, 203, 5411, 262, 16, 203, 5411, 3847, 203, 1850, 262, 203, 3639, 262, 203, 3639, 1663, 5263, 519, 312, 945, 12, 1105, 13, 203, 3639, 312, 2233, 12, 1105, 16, 527, 12, 3917, 5263, 16, 14426, 2891, 3719, 203, 3639, 745, 892, 3530, 12, 3917, 5263, 16, 745, 892, 5263, 16, 14426, 2891, 13, 203, 3639, 745, 892, 5263, 519, 527, 12, 1991, 892, 5263, 16, 14426, 2891, 13, 203, 1377, 289, 203, 203, 1377, 2231, 745, 892, 5263, 519, 720, 12, 1467, 951, 1616, 16, 745, 72, 3145, 6189, 12, 1467, 951, 1616, 3719, 203, 203, 1377, 389, 31734, 519, 745, 72, 3145, 6189, 12, 1991, 892, 5263, 13, 203, 1377, 745, 892, 5263, 519, 527, 12, 1991, 892, 5263, 16, 3847, 13, 203, 203, 1377, 389, 4963, 3088, 1283, 519, 745, 72, 3145, 6189, 12, 1991, 892, 5263, 13, 203, 1377, 745, 892, 5263, 519, 527, 12, 1991, 892, 5263, 16, 3847, 13, 203, 203, 1377, 389, 4308, 6581, 519, 745, 72, 3145, 6189, 12, 1991, 892, 5263, 13, 203, 1377, 745, 892, 5263, 519, 527, 12, 2 ]
./partial_match/1/0xc4d57603D47FB842EC11A5332748f9F96d44cbEB/sources/src/contracts/FraxlendPairCore.sol
@notice The ```_deposit``` function is the internal implementation for lending assets @dev Caller must invoke ```ERC20.approve``` on the Asset Token contract prior to calling function @param _totalAsset An in memory VaultAccount struct representing the total amounts and shares for the Asset Token @param _amount The amount of Asset Token to be transferred @param _shares The amount of Asset Shares (fTokens) to be minted @param _receiver The address to receive the Asset Shares (fTokens) Effects: bookkeeping Effects: write back to storage Interactions
function _deposit( VaultAccount memory _totalAsset, uint128 _amount, uint128 _shares, address _receiver ) internal { _totalAsset.amount += _amount; _totalAsset.shares += _shares; _mint(_receiver, _shares); totalAsset = _totalAsset; assetContract.safeTransferFrom(msg.sender, address(this), _amount); emit Deposit(msg.sender, _receiver, _amount, _shares); }
3,702,605
[ 1, 1986, 31621, 67, 323, 1724, 10335, 68, 445, 353, 326, 2713, 4471, 364, 328, 2846, 7176, 225, 20646, 1297, 4356, 31621, 654, 39, 3462, 18, 12908, 537, 10335, 68, 603, 326, 10494, 3155, 6835, 6432, 358, 4440, 445, 225, 389, 4963, 6672, 1922, 316, 3778, 17329, 3032, 1958, 5123, 326, 2078, 30980, 471, 24123, 364, 326, 10494, 3155, 225, 389, 8949, 1021, 3844, 434, 10494, 3155, 358, 506, 906, 4193, 225, 389, 30720, 1021, 3844, 434, 10494, 2638, 4807, 261, 74, 5157, 13, 358, 506, 312, 474, 329, 225, 389, 24454, 1021, 1758, 358, 6798, 326, 10494, 2638, 4807, 261, 74, 5157, 13, 30755, 87, 30, 6978, 10102, 310, 30755, 87, 30, 1045, 1473, 358, 2502, 5294, 4905, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 323, 1724, 12, 203, 3639, 17329, 3032, 3778, 389, 4963, 6672, 16, 203, 3639, 2254, 10392, 389, 8949, 16, 203, 3639, 2254, 10392, 389, 30720, 16, 203, 3639, 1758, 389, 24454, 203, 565, 262, 2713, 288, 203, 3639, 389, 4963, 6672, 18, 8949, 1011, 389, 8949, 31, 203, 3639, 389, 4963, 6672, 18, 30720, 1011, 389, 30720, 31, 203, 203, 3639, 389, 81, 474, 24899, 24454, 16, 389, 30720, 1769, 203, 3639, 2078, 6672, 273, 389, 4963, 6672, 31, 203, 203, 3639, 3310, 8924, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 3639, 3626, 4019, 538, 305, 12, 3576, 18, 15330, 16, 389, 24454, 16, 389, 8949, 16, 389, 30720, 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 ]
pragma solidity 0.6.12; import "./lib/BEP20.sol"; import "./interface/IMintBurnToken.sol"; contract aLBNB2BNBLP is BEP20, IMintBurnToken { constructor(address ownerAddr) public { super.initializeBEP20("Aged LBNB2BNB LP", "aLBNB2BNB", 18, 0, ownerAddr); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (SteakBank). function mintTo(address _to, uint256 _amount) override external onlyOwner returns (bool) { _mint(_to, _amount); return true; } /** * @dev Burn `amount` tokens and decreasing the total supply. */ function burn(uint256 amount) override external returns (bool) { _burn(_msgSender(), amount); return true; } }
@notice Creates `_amount` token to `_to`. Must only be called by the owner (SteakBank).
function mintTo(address _to, uint256 _amount) override external onlyOwner returns (bool) { _mint(_to, _amount); return true; }
12,990,273
[ 1, 2729, 1375, 67, 8949, 68, 1147, 358, 1375, 67, 869, 8338, 6753, 1338, 506, 2566, 635, 326, 3410, 261, 510, 73, 581, 16040, 2934, 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 ]
[ 1, 1, 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 ]
[ 1, 565, 445, 312, 474, 774, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 3849, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 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 ]
// SPDX-License-Identifier: MIT // The following contract is a simplified version of https://github.com/rstormsf/multisender. pragma solidity >=0.6.0 <0.7.0; contract Multisend { event Multisended(address indexed _from, address[] _to, uint256[] _value); event FeeChanged(uint256 _fee); event AuthorizedAddrChanged(address _newAuthorizedAddr); event Withdrawn(address indexed receiver, uint256 amount); uint256 internal contractFee = 0 ether; // A contract-caller has to pay this fee to get service address internal authorizedAddr; constructor() public { authorizedAddr = msg.sender; } function changeFee(uint256 fee) public { require(msg.sender == authorizedAddr, "You are not authorized."); contractFee = fee; emit FeeChanged(fee); } function changeAuthorizedAddr(address newAuthorizedAddr) public { require(msg.sender == authorizedAddr, "You are not authorized."); authorizedAddr = newAuthorizedAddr; emit AuthorizedAddrChanged(newAuthorizedAddr); } function withdraw(address payable receiver) public { require(msg.sender == authorizedAddr, "You are not authorized."); uint256 amount = address(this).balance; emit Withdrawn(receiver, amount); receiver.transfer(amount); } function multisendEther(address[] memory receivers, uint256[] memory amounts) public payable { uint256 total = msg.value; require(total >= contractFee, "Do not have enough tokens to pay the contract fee."); total = total - contractFee; uint256 i = 0; for (i; i < receivers.length; i++) { require(total >= amounts[i], "Do not have enough tokens to send."); total = total - amounts[i]; address payable receiver = address(uint160(receivers[i])); receiver.transfer(amounts[i]); } emit Multisended(msg.sender, receivers, amounts); } function checkContractFee() public view returns(uint){ return contractFee; } function checkAuthorizedAddr() public view returns(address){ return authorizedAddr; } }
SPDX-License-Identifier: MIT The following contract is a simplified version of https:github.com/rstormsf/multisender.
pragma solidity >=0.6.0 <0.7.0;
150,616
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 1021, 3751, 6835, 353, 279, 20482, 1177, 434, 2333, 30, 6662, 18, 832, 19, 16114, 535, 21668, 19, 23978, 2345, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 20, 411, 20, 18, 27, 18, 20, 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 ]
./full_match/1/0xC774ff15E66C2B1b58225EfA821765119bC2D131/sources/ZKDOGE.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 { Secure your transactions, protect your privacy with ZKDOGE - the future of cryptocurrency. function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
8,425,477
[ 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, 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, 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, 17801, 6835, 1772, 288, 203, 12834, 3433, 8938, 16, 17151, 3433, 19013, 598, 29878, 3191, 7113, 300, 326, 3563, 434, 13231, 504, 295, 3040, 18, 203, 203, 203, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 5024, 1135, 261, 2867, 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, 745, 892, 13, 288, 203, 3639, 327, 1234, 18, 892, 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 ]
pragma solidity 0.5.10; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import './FundsInterface.sol'; import './SalesInterface.sol'; import './CollateralInterface.sol'; import './DSMath.sol'; import './Medianizer.sol'; /** * @title Atomic Loans Loans Contract * @author Atomic Loans */ contract Loans is DSMath { FundsInterface funds; Medianizer med; SalesInterface sales; CollateralInterface col; uint256 public constant APPROVE_EXP_THRESHOLD = 4 hours; // approval expiration threshold uint256 public constant ACCEPT_EXP_THRESHOLD = 2 days; // acceptance expiration threshold uint256 public constant LIQUIDATION_EXP_THRESHOLD = 7 days; // liquidation expiration threshold uint256 public constant SEIZURE_EXP_THRESHOLD = 2 days; // seizable expiration threshold uint256 public constant LIQUIDATION_DISCOUNT = 930000000000000000; // 93% (7% discount) uint256 public constant MAX_NUM_LIQUIDATIONS = 3; // Maximum number of liquidations that can occur uint256 public constant MAX_UINT_256 = 2**256-1; mapping (bytes32 => Loan) public loans; mapping (bytes32 => PubKeys) public pubKeys; // Bitcoin Public Keys mapping (bytes32 => SecretHashes) public secretHashes; // Secret Hashes mapping (bytes32 => Bools) public bools; // Boolean state of Loan mapping (bytes32 => bytes32) public fundIndex; // Mapping of Loan Index to Fund Index mapping (bytes32 => uint256) public repayments; // Amount paid back in a Loan mapping (address => bytes32[]) public borrowerLoans; mapping (address => bytes32[]) public lenderLoans; mapping (address => mapping(uint256 => bool)) public addressToTimestamp; uint256 public loanIndex; // Current Loan Index ERC20 public token; // ERC20 Debt Stablecoin uint256 public decimals; address deployer; /** * @notice Container for loan information * @member borrower The address of the borrower * @member lender The address of the lender * @member arbiter The address of the arbiter * @member createdAt The creation timestamp of the loan * @member loanExpiration The timestamp for the end of the loan * @member requestTimestamp The timestamp for when the loan is requested * @member closedTimestamp The timestamp for when the loan is closed * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member principal The amount of principal in tokens to be paid back at the end of the loan * @member interest The amount of interest in tokens to be paid back by the end of the loan * @member penalty The amount of tokens to be paid as a penalty for defaulting or allowing the loan to be liquidated * @member fee The amount of tokens paid to the arbiter * @member liquidationRatio The ratio of collateral to debt where the loan can be liquidated */ struct Loan { address borrower; address lender; address arbiter; uint256 createdAt; uint256 loanExpiration; uint256 requestTimestamp; uint256 closedTimestamp; uint256 principal; uint256 interest; uint256 penalty; uint256 fee; uint256 liquidationRatio; } /** * @notice Container for Bitcoin public key information * @member borrowerPubKey Borrower Bitcoin Public Key * @member lenderPubKey Lender Bitcoin Public Key * @member arbiterPubKey Arbiter Bitcoin Public Key * * Note: This struct is unnecessary for the Ethereum * contract itself, but is used as a point of * reference for generating the correct P2WSH for * locking Bitcoin collateral */ struct PubKeys { bytes borrowerPubKey; bytes lenderPubKey; bytes arbiterPubKey; } /** * @notice Container for borrower, lender, and arbiter Secret Hashes * @member secretHashA1 Borrower Secret Hash for the loan * @member secretHashAs Borrower Secret Hashes for up to three liquidations * @member secretHashB1 Lender Secret Hash for the loan * @member secretHashBs Lender Secret Hashes for up to three liquidations * @member secretHashC1 Arbiter Secret Hash for the loan * @member secretHashCs Arbiter Secret Hashes for up to three liquidations * @member withdrawSecret Secret A1 when revealed by borrower * @member acceptSecret Secret B1 or Secret C1 when revelaed by the lender or arbiter * @member set Secret Hashes set for particular loan */ struct SecretHashes { bytes32 secretHashA1; bytes32[3] secretHashAs; bytes32 secretHashB1; bytes32[3] secretHashBs; bytes32 secretHashC1; bytes32[3] secretHashCs; bytes32 withdrawSecret; bytes32 acceptSecret; bool set; } /** * @notice Container for states of loan agreement * @member funded Indicates that the loan has been funded with tokens * @member approved Indicates that the lender has approved locking of the Bitcoin collateral * @member withdrawn Indicates that the borrower has withdrawn the tokens from the contract * @member sale Indicates that the collateral liquidation process has started * @member paid Indicates that the loan has been repaid * @member off Indicates that the loan has been cancelled or the loan repayment has been accepted */ struct Bools { bool funded; bool approved; bool withdrawn; bool sale; bool paid; bool off; } event Create(bytes32 loan); event SetSecretHashes(bytes32 loan); event FundLoan(bytes32 loan); event Approve(bytes32 loan); event Withdraw(bytes32 loan, bytes32 secretA1); event Repay(bytes32 loan, uint256 amount); event Refund(bytes32 loan); event Cancel(bytes32 loan, bytes32 secret); event Accept(bytes32 loan, bytes32 secret); event Liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); /** * @notice Get the Borrower of a Loan * @param loan The Id of a Loan * @return Borrower address of Loan */ function borrower(bytes32 loan) external view returns (address) { return loans[loan].borrower; } /** * @notice Get the Lender of a Loan * @param loan The Id of a Loan * @return Lender address of Loan */ function lender(bytes32 loan) external view returns (address) { return loans[loan].lender; } /** * @notice Get the Arbiter of a Loan * @param loan The Id of a Loan * @return Arbiter address of Loan */ function arbiter(bytes32 loan) external view returns (address) { return loans[loan].arbiter; } /** * @notice Get the Approve Expiration of a Loan * @param loan The Id of a Loan * @return Approve Expiration Timestamp */ function approveExpiration(bytes32 loan) public view returns (uint256) { // Approval Expiration return add(loans[loan].createdAt, APPROVE_EXP_THRESHOLD); } /** * @notice Get the Accept Expiration of a Loan * @param loan The Id of a Loan * @return Accept Expiration Timestamp */ function acceptExpiration(bytes32 loan) public view returns (uint256) { // Acceptance Expiration return add(loans[loan].loanExpiration, ACCEPT_EXP_THRESHOLD); } /** * @notice Get the Liquidation Expiration of a Loan * @param loan The Id of a Loan * @return Liquidation Expiration Timestamp */ function liquidationExpiration(bytes32 loan) public view returns (uint256) { // Liquidation Expiration return add(loans[loan].loanExpiration, LIQUIDATION_EXP_THRESHOLD); } /** * @notice Get the Seizure Expiration of a Loan * @param loan The Id of a Loan * @return Seizure Expiration Timestamp */ function seizureExpiration(bytes32 loan) public view returns (uint256) { return add(liquidationExpiration(loan), SEIZURE_EXP_THRESHOLD); } /** * @notice Get the Principal of a Loan * @param loan The Id of a Loan * @return Amount of Principal in stablecoin tokens */ function principal(bytes32 loan) public view returns (uint256) { return loans[loan].principal; } /** * @notice Get the Interest of a Loan * @param loan The Id of a Loan * @return Amount of Interest in stablecoin tokens */ function interest(bytes32 loan) public view returns (uint256) { return loans[loan].interest; } /** * @notice Get the Fee of a Loan * @param loan The Id of a Loan * @return Amount of Fee in stablecoin tokens */ function fee(bytes32 loan) public view returns (uint256) { return loans[loan].fee; } /** * @notice Get the Penalty of a Loan (if not repaid) * @dev Upon liquidation penalty is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount of Penalty in stablecoin tokens */ function penalty(bytes32 loan) public view returns (uint256) { return loans[loan].penalty; } /** * @notice Get the Collateral of a Loan * @param loan The Id of a Loan * @return Amount of collateral backing the loan (in sats) */ function collateral(bytes32 loan) public view returns (uint256) { return col.collateral(loan); } /** * @notice Get the Refundable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of refundable collateral backing the loan (in sats) */ function refundableCollateral(bytes32 loan) external view returns (uint256) { return col.refundableCollateral(loan); } /** * @notice Get the Seizable Collateral of a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral backing the loan (in sats) */ function seizableCollateral(bytes32 loan) external view returns (uint256) { return col.seizableCollateral(loan); } /** * @notice Get the Temporary Refundable Collateral of a Loan * @dev Represents the amount of refundable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary refundable collateral backing the loan (in sats) */ function temporaryRefundableCollateral(bytes32 loan) external view returns (uint256) { return col.temporaryRefundableCollateral(loan); } /** * @notice Get the Temporary Seizable Collateral of a Loan * @dev Represents the amount of seizable collateral that has been locked and only has 1 conf, where 6 confs hasn't been received yet * @param loan The Id of a Loan * @return Amount of temporary seizable collateral backing the loan (in sats) */ function temporarySeizableCollateral(bytes32 loan) external view returns (uint256) { return col.temporarySeizableCollateral(loan); } /** * @notice Get the amount repaid towards a Loan * @param loan The Id of a Loan * @return Amount of the loan that has been repaid */ function repaid(bytes32 loan) public view returns (uint256) { // Amount paid back for loan return repayments[loan]; } /** * @notice Get Liquidation Ratio of a Loan (Minimum Collateralization Ratio) * @param loan The Id of a Loan * @return Liquidation Ratio in RAY (i.e. 140% would be 1.4 * (10 ** 27)) */ function liquidationRatio(bytes32 loan) public view returns (uint256) { return loans[loan].liquidationRatio; } /** * @notice Get the amount owed to the Lender for a Loan * @param loan The Id of a Loan * @return Amount owed to the Lender */ function owedToLender(bytes32 loan) public view returns (uint256) { // Amount lent by Lender return add(principal(loan), interest(loan)); } /** * @notice Get the amount needed to repay a Loan * @param loan The Id of a Loan * @return Amount needed to repay the Loan */ function owedForLoan(bytes32 loan) public view returns (uint256) { // Amount owed return add(owedToLender(loan), fee(loan)); } /** * @notice Get the amount that needs to be covered in the case of a liquidation for a Loan * @dev owedForLiquidation includes penalty which is paid out to oracles to give incentive for users to continue updating them * @param loan The Id of a Loan * @return Amount needed to cover a liquidation */ function owedForLiquidation(bytes32 loan) external view returns (uint256) { // Deductible amount from collateral return add(owedForLoan(loan), penalty(loan)); } /** * @notice Get the amount still owing for a Loan * @param loan The Id of a Loan * @return Amount owing for a Loan */ function owing(bytes32 loan) external view returns (uint256) { return sub(owedForLoan(loan), repaid(loan)); } /** * @notice Get the funded status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been funded */ function funded(bytes32 loan) external view returns (bool) { return bools[loan].funded; } /** * @notice Get the approved status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been approved */ function approved(bytes32 loan) external view returns (bool) { return bools[loan].approved; } /** * @notice Get the withdrawn status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been withdrawn */ function withdrawn(bytes32 loan) external view returns (bool) { return bools[loan].withdrawn; } /** * @notice Get the sale status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been liquidated */ function sale(bytes32 loan) public view returns (bool) { return bools[loan].sale; } /** * @notice Get the paid status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been repaid */ function paid(bytes32 loan) external view returns (bool) { return bools[loan].paid; } /** * @notice Get the off status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan has been terminated */ function off(bytes32 loan) public view returns (bool) { return bools[loan].off; } /** * @notice Decimal multiplication that multiplies the number to 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal multiply * @return x converted to WAD (10 ** 18) if decimals are less than 18, else x */ function dmul(uint x) public view returns (uint256) { return mul(x, (10 ** sub(18, decimals))); } /** * @notice Decimal division that divides the number to 10 ** decimals from 10 ** 18 if stablecoin token decimals are less than 18 * @param x The number to decimal divide * @return x converted to 10 ** decimals if decimals are less than 18, else x */ function ddiv(uint x) public view returns (uint256) { return div(x, (10 ** sub(18, decimals))); } /** * @notice Get the number of loans originated by a Borrower * @param borrower_ Address of the Borrower * @return Number of loans originated by Borrower */ function borrowerLoanCount(address borrower_) external view returns (uint256) { return borrowerLoans[borrower_].length; } /** * @notice Get the number of loans originated by a Lender * @param lender_ Address of the Lender * @return Number of loans originated by Lender */ function lenderLoanCount(address lender_) external view returns (uint256) { return lenderLoans[lender_].length; } /** * @notice The minimum seizable collateral required to cover a Loan * @param loan The Id of a Loan * @return Amount of seizable collateral value (in sats) required to cover a Loan */ function minSeizableCollateral(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.minSeizableCollateral: Medianizer must be set"); uint256 price = uint(val); return div(wdiv(dmul(sub(owedForLoan(loan), repaid(loan))), price), div(WAD, COL)); } /** * @notice The current collateral value of a Loan * @dev Gets the price in USD from the Medianizer and multiplies it by the collateral in sats to get the USD value of collateral * @param loan The Id of a Loan * @return Value of collateral (USD in WAD) */ function collateralValue(bytes32 loan) public view returns (uint256) { (bytes32 val, bool set) = med.peek(); require(set, "Loans.collateralValue: Medianizer must be set"); uint256 price = uint(val); return cmul(price, collateral(loan)); } /** * @notice The minimum collateral value to cover the amount owed for a Loan * @dev Gets the amount in the Loan that still needs to be repaid, converts to WAD, and multiplies it by the minimum liquidation ratio * @param loan The Id of a Loan * @return Value of the minimum collateral required (USD in WAD) */ function minCollateralValue(bytes32 loan) public view returns (uint256) { return rmul(dmul(sub(owedForLoan(loan), repaid(loan))), liquidationRatio(loan)); } /** * @notice The discount collateral value in which a Liquidator can purchase the collateral for * @param loan The Id of a Loan * @return Value of the discounted collateral required to Liquidate a Loan (USD in WAD) */ function discountCollateralValue(bytes32 loan) public view returns (uint256) { return wmul(collateralValue(loan), LIQUIDATION_DISCOUNT); } /** * @notice Get the safe status of a Loan * @param loan The Id of a Loan * @return Bool that indicates whether loan is safe from liquidation */ function safe(bytes32 loan) public view returns (bool) { return collateralValue(loan) >= minCollateralValue(loan); } /** * @notice Construct a new Loans contract * @param funds_ The address of the Funds contract * @param med_ The address of the Medianizer contract * @param token_ The stablecoin token address * @param decimals_ The number of decimals in the stablecoin token */ constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public { require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = msg.sender; funds = funds_; med = med_; token = token_; decimals = decimals_; require(token.approve(address(funds), MAX_UINT_256), "Token approve failed"); } // NOTE: THE FOLLOWING FUNCTIONS CAN ONLY BE CALLED BY THE DEPLOYER OF THE // CONTRACT ONCE. THIS IS TO ALLOW FOR FUNDS, LOANS, AND SALES // CONTRACTS TO BE DEPLOYED SEPARATELY (DUE TO GAS LIMIT RESTRICTIONS). // IF YOU ARE USING THIS CONTRACT, ENSURE THAT THESE FUNCTIONS HAVE // ALREADY BEEN CALLED BEFORE DEPOSITING FUNDS. // ====================================================================== /** * @dev Sets Sales contract * @param sales_ Address of Sales contract */ function setSales(SalesInterface sales_) external { require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this"); require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set"); require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero"); sales = sales_; } /** * @dev Sets Spv contract * @param col_ Address of Collateral contract */ function setCollateral(CollateralInterface col_) external { require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this"); require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set"); require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero"); col = col_; } // ====================================================================== /** * @notice Creates a new loan agreement * @param loanExpiration_ The timestamp for the end of the loan * @param usrs_ Array of three addresses containing the borrower, lender, and optional arbiter address * @param vals_ Array of seven uints containing loan principal, interest, liquidation penalty, optional arbiter fee, collateral amount, liquidation ratio, and request timestamp * @param fund The optional Fund ID */ function create( uint256 loanExpiration_, address[3] calldata usrs_, uint256[7] calldata vals_, bytes32 fund ) external returns (bytes32 loan) { if (fund != bytes32(0)) { require(funds.lender(fund) == usrs_[1], "Loans.create: Lender of Fund not in args"); } require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed"); require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`"); require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero"); require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero"); require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero"); loanIndex = add(loanIndex, 1); loan = bytes32(loanIndex); loans[loan].createdAt = now; loans[loan].loanExpiration = loanExpiration_; loans[loan].borrower = usrs_[0]; loans[loan].lender = usrs_[1]; loans[loan].arbiter = usrs_[2]; loans[loan].principal = vals_[0]; loans[loan].interest = vals_[1]; loans[loan].penalty = vals_[2]; loans[loan].fee = vals_[3]; uint256 minSeizableCol = minSeizableCollateral(loan); col.setCollateral(loan, sub(vals_[4], minSeizableCol), minSeizableCol); loans[loan].liquidationRatio = vals_[5]; loans[loan].requestTimestamp = vals_[6]; fundIndex[loan] = fund; secretHashes[loan].set = false; borrowerLoans[usrs_[0]].push(bytes32(loanIndex)); lenderLoans[usrs_[1]].push(bytes32(loanIndex)); addressToTimestamp[usrs_[0]][vals_[6]] = true; emit Create(loan); } /** * @notice Set Secret Hashes for loan agreement * @param loan The Id of the Loan * @param borrowerSecretHashes Borrower secret hashes * @param lenderSecretHashes Lender secret hashes * @param arbiterSecretHashes Arbiter secret hashes * @param borrowerPubKey_ Borrower Bitcoin Public Key * @param lenderPubKey_ Lender Bitcoin Public Key * @param arbiterPubKey_ Arbiter Bitcoin Public Key */ function setSecretHashes( bytes32 loan, bytes32[4] calldata borrowerSecretHashes, bytes32[4] calldata lenderSecretHashes, bytes32[4] calldata arbiterSecretHashes, bytes calldata borrowerPubKey_, bytes calldata lenderPubKey_, bytes calldata arbiterPubKey_ ) external { require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set"); require( msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds), "Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address" ); secretHashes[loan].secretHashA1 = borrowerSecretHashes[0]; secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ]; secretHashes[loan].secretHashB1 = lenderSecretHashes[0]; secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ]; secretHashes[loan].secretHashC1 = arbiterSecretHashes[0]; secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ]; pubKeys[loan].borrowerPubKey = borrowerPubKey_; pubKeys[loan].lenderPubKey = lenderPubKey_; pubKeys[loan].arbiterPubKey = arbiterPubKey_; secretHashes[loan].set = true; } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan */ function fund(bytes32 loan) external { require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set"); require(bools[loan].funded == false, "Loans.fund: Loan is already funded"); bools[loan].funded = true; require(token.transferFrom(msg.sender, address(this), principal(loan)), "Loans.fund: Failed to transfer tokens"); emit FundLoan(loan); } /** * @notice Lender approves locking of Bitcoin collateral * @param loan The Id of the Loan */ function approve(bytes32 loan) external { // Approve locking of collateral require(bools[loan].funded == true, "Loans.approve: Loan must be funded"); require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan"); require(now <= approveExpiration(loan), "Loans.approve: Loan is past the approve deadline"); bools[loan].approved = true; emit Approve(loan); } /** * @notice Borrower withdraws loan * @param loan The Id of the Loan * @param secretA1 Secret A1 provided by the borrower */ function withdraw(bytes32 loan, bytes32 secretA1) external { require(!off(loan), "Loans.withdraw: Loan cannot be inactive"); require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded"); require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved"); require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn"); require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match"); bools[loan].withdrawn = true; require(token.transfer(loans[loan].borrower, principal(loan)), "Loans.withdraw: Failed to transfer tokens"); secretHashes[loan].withdrawSecret = secretA1; if (address(col.onDemandSpv()) != address(0)) {col.requestSpv(loan);} emit Withdraw(loan, secretA1); } /** * @notice Lender sends tokens to the loan agreement * @param loan The Id of the Loan * @param amount The amount of tokens to repay * * Note: Anyone can repay the loan */ function repay(bytes32 loan, uint256 amount) external { require(!off(loan), "Loans.repay: Loan cannot be inactive"); require(!sale(loan), "Loans.repay: Loan cannot be undergoing a liquidation"); require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn"); require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired"); require(add(amount, repaid(loan)) <= owedForLoan(loan), "Loans.repay: Cannot repay more than the owed amount"); require(token.transferFrom(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens"); repayments[loan] = add(amount, repayments[loan]); if (repaid(loan) == owedForLoan(loan)) { bools[loan].paid = true; if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} } emit Repay(loan, amount); } /** * @notice Borrower refunds tokens in the case that Lender doesn't accept loan repayment * @dev Send tokens back to the Borrower, and close Loan * @param loan The Id of the Loan * * Note: If Lender does not accept repayment, liquidation cannot occur */ function refund(bytes32 loan) external { require(!off(loan), "Loans.refund: Loan cannot be inactive"); require(!sale(loan), "Loans.refund: Loan cannot be undergoing a liquidation"); require(now > acceptExpiration(loan), "Loans.refund: Cannot request refund until after acceptExpiration"); require(bools[loan].paid == true, "Loans.refund: The loan must be repaid"); require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund"); bools[loan].off = true; loans[loan].closedTimestamp = now; if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } require(token.transfer(loans[loan].borrower, owedForLoan(loan)), "Loans.refund: Failed to transfer tokens"); emit Refund(loan); } /** * @notice Lender cancels loan after Borrower locks collateral * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function cancel(bytes32 loan, bytes32 secret) external { accept(loan, secret); emit Cancel(loan, secret); } /** * @notice Lender cancels loan after Seizure Expiration in case Lender loses secret * @dev Lender cancels loan and principal is sent back to the Lender / Loan Fund * @param loan The Id of the Loan */ function cancel(bytes32 loan) external { require(!off(loan), "Loans.cancel: Loan must not be inactive"); require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn"); require(now >= seizureExpiration(loan), "Loans.cancel: Seizure deadline has not been reached"); require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation"); close(loan); emit Cancel(loan, bytes32(0)); } /** * @notice Lender accepts loan repayment * @dev Lender accepts loan repayment and principal + interest are sent back to the Lender / Loan Fund * @param loan The Id of the Loan * @param secret Secret B1 revealed by the Lender */ function accept(bytes32 loan, bytes32 secret) public { require(!off(loan), "Loans.accept: Loan must not be inactive"); require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid"); require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter"); require(now <= acceptExpiration(loan), "Loans.accept: Acceptance deadline has past"); require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation"); require( sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1, "Loans.accept: Invalid secret" ); secretHashes[loan].acceptSecret = secret; close(loan); emit Accept(loan, secret); } /** * @notice Terminate Loan and transfer funds back to Lender and Arbiter (if there are any fees acrued) * @param loan The Id of the Loan */ function close(bytes32 loan) private { bools[loan].off = true; loans[loan].closedTimestamp = now; // If Loan has not been withdraw, simply transfer Principal back to the Lender if (bools[loan].withdrawn == false) { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], loans[loan].principal); } } // If Loan has been withdrawn, transfer Principal + Interest to Lender and Fee to Arbiter else { if (fundIndex[loan] == bytes32(0)) { require(token.transfer(loans[loan].lender, owedToLender(loan)), "Loans.close: Failed to transfer owedToLender to Lender"); } else { if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); } funds.deposit(fundIndex[loan], owedToLender(loan)); } require(token.transfer(loans[loan].arbiter, fee(loan)), "Loans.close: Failed to transfer fee to Arbiter"); } } /** * @notice Any third party starts liquidation of the Bitcoin collateral by providing tokens with the intention to buy at a discount * @param loan The Id of the Loan * @param secretHash The Secret Hash D1 provided by the liquidator * @param pubKeyHash The Bitcoin Public Key Hash of the liquidator * @return sale_ The Id of the Sale (Liquidation) */ function liquidate(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { require(!off(loan), "Loans.liquidate: Loan must not be inactive"); require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn"); require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party"); require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero"); // Check if this is the first liquidation (if a liquidation fails because the liquidator didn't claim, up to MAX_NUM_LIQUIDATIONS can occur) if (sales.next(loan) == 0) { // Check if current time is greater than loan expiration timestamp if (now > loans[loan].loanExpiration) { require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid"); } else { require(!safe(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio"); } // If Loan is not custom, update global borrow and interest variables in Funds contract if (funds.custom(fundIndex[loan]) == false) { funds.decreaseTotalBorrow(loans[loan].principal); funds.calcGlobalInterest(); } } else { // Since there is only 1 + MAX_NUM_LIQUIDATIONS secret hashes per participant, only MAX_NUM_LIQUIDATIONS Liquidation can occur require(sales.next(loan) < MAX_NUM_LIQUIDATIONS, "Loans.liquidate: Max number of liquidations reached"); require(!sales.accepted(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted"); require( now > sales.settlementExpiration(sales.saleIndexByLoan(loan, sales.next(loan) - 1)), "Loans.liquidate: Previous liquidation settlement expiration hasn't expired" ); } require(token.balanceOf(msg.sender) >= ddiv(discountCollateralValue(loan)), "Loans.liquidate: insufficient balance to liquidate"); require(token.transferFrom(msg.sender, address(sales), ddiv(discountCollateralValue(loan))), "Loans.liquidate: Token transfer failed"); SecretHashes storage h = secretHashes[loan]; uint256 i = sales.next(loan); // Create new Sale with secret hashes associated with sale index sale_ = sales.create( loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender, h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash ); if (bools[loan].sale == false) { bools[loan].sale = true; require(token.transfer(address(sales), repaid(loan)), "Loans.liquidate: Token transfer to Sales contract failed"); } // If onDemandSpv is set, cancel spv proofs for this Loan if (address(col.onDemandSpv()) != address(0)) {col.cancelSpv(loan);} emit Liquidate(loan, secretHash, pubKeyHash); } }
* @notice Get the approved status of a Loan @param loan The Id of a Loan @return Bool that indicates whether loan has been approved/
function approved(bytes32 loan) external view returns (bool) { return bools[loan].approved; }
7,298,209
[ 1, 967, 326, 20412, 1267, 434, 279, 3176, 304, 225, 28183, 1021, 3124, 434, 279, 3176, 304, 327, 9166, 716, 8527, 2856, 28183, 711, 2118, 20412, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 20412, 12, 3890, 1578, 28183, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1426, 87, 63, 383, 304, 8009, 25990, 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 ]
./full_match/1/0x4E5b0cDC255D8DC0B4bB190429b60487C10205B4/sources/DVT.sol
uint256 tMarketing,
function _getRTransferAmount( uint256 rAmount, uint256 rFee, uint256 tLiquidity, uint256 tCharity, uint256 currentRate ) private pure returns (uint256) { uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rCharity = tCharity.mul(currentRate); uint256 temp = rAmount.sub(rFee).sub(rLiquidity).sub(rCharity); return temp; }
3,033,490
[ 1, 11890, 5034, 268, 3882, 21747, 16, 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, 389, 588, 54, 5912, 6275, 12, 203, 3639, 2254, 5034, 436, 6275, 16, 203, 3639, 2254, 5034, 436, 14667, 16, 203, 3639, 2254, 5034, 268, 48, 18988, 24237, 16, 203, 3639, 2254, 5034, 268, 2156, 560, 16, 203, 3639, 2254, 5034, 783, 4727, 203, 565, 262, 3238, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 436, 48, 18988, 24237, 273, 268, 48, 18988, 24237, 18, 16411, 12, 2972, 4727, 1769, 203, 3639, 2254, 5034, 436, 2156, 560, 273, 268, 2156, 560, 18, 16411, 12, 2972, 4727, 1769, 203, 3639, 2254, 5034, 1906, 273, 436, 6275, 18, 1717, 12, 86, 14667, 2934, 1717, 12, 86, 48, 18988, 24237, 2934, 1717, 12, 86, 2156, 560, 1769, 203, 3639, 327, 1906, 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 ]
pragma solidity ^0.4.18; /** * @title ERC721 interface * @dev see https://github.com/ethereum/eips/issues/721 */ contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title 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; mapping (address => bool) public admins; 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; admins[owner] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyAdmin() { require(admins[msg.sender]); _; } function changeAdmin(address _newAdmin, bool _approved) onlyOwner public { admins[_newAdmin] = _approved; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC721Token * Generic implementation for the required functionality of the ERC721 standard */ contract ArkToken is ERC721, Ownable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; uint256 public developerCut; // Animal Data mapping (uint256 => Animal) public arkData; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // mom ID => baby ID mapping (uint256 => uint256) public babies; // baby ID => parents mapping (uint256 => uint256[2]) public babyMommas; // token ID => their baby-makin' partner mapping (uint256 => uint256) public mates; // baby ID => sum price of mom and dad needed to make this babby mapping (uint256 => uint256) public babyMakinPrice; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; // Balances from % payouts. mapping (address => uint256) public birtherBalances; // Events event Purchase(uint256 indexed _tokenId, address indexed _buyer, address indexed _seller, uint256 _purchasePrice); event Birth(address indexed _birther, uint256 indexed _mom, uint256 _dad, uint256 indexed _baby); // Purchasing Caps for Determining Next Pool Cut uint256 private firstCap = 0.5 ether; uint256 private secondCap = 1.0 ether; uint256 private thirdCap = 1.5 ether; uint256 private finalCap = 3.0 ether; // Struct to store Animal Data struct Animal { uint256 price; // Current price of the item. uint256 lastPrice; // Last price needed to calculate whether baby-makin' limit has made it address owner; // Current owner of the item. address birther; // Address that birthed the animal. uint256 birtherPct; // Percent that birther will get for sales. The actual percent is this / 10. uint8 gender; // Gender of this animal: 0 for male, 1 for female. } function createToken(uint256 _tokenId, uint256 _startingPrice, uint256 _cut, address _owner, uint8 _gender) onlyAdmin() public { // make sure price > 0 require(_startingPrice > 0); // make sure token hasn't been used yet require(arkData[_tokenId].price == 0); // create new token Animal storage curAnimal = arkData[_tokenId]; curAnimal.owner = _owner; curAnimal.price = _startingPrice; curAnimal.lastPrice = _startingPrice; curAnimal.gender = _gender; curAnimal.birther = _owner; curAnimal.birtherPct = _cut; // mint new token _mint(_owner, _tokenId); } function createMultiple (uint256[] _itemIds, uint256[] _prices, uint256[] _cuts, address[] _owners, uint8[] _genders) onlyAdmin() external { for (uint256 i = 0; i < _itemIds.length; i++) { createToken(_itemIds[i], _prices[i], _cuts[i], _owners[i], _genders[i]); } } function createBaby(uint256 _dad, uint256 _mom, uint256 _baby, uint256 _price) public onlyAdmin() { mates[_mom] = _dad; mates[_dad] = _mom; babies[_mom] = _baby; babyMommas[_baby] = [_mom, _dad]; babyMakinPrice[_baby] = _price; } function createBabies(uint256[] _dads, uint256[] _moms, uint256[] _babies, uint256[] _prices) external onlyAdmin() { require(_moms.length == _babies.length && _babies.length == _dads.length); for (uint256 i = 0; i < _moms.length; i++) { createBaby(_dads[i], _moms[i], _babies[i], _prices[i]); } } /** * @dev Determines next price of token * @param _price uint256 ID of current price */ function getNextPrice (uint256 _price) private view returns (uint256 _nextPrice) { if (_price < firstCap) { return _price.mul(150).div(95); } else if (_price < secondCap) { return _price.mul(135).div(96); } else if (_price < thirdCap) { return _price.mul(125).div(97); } else if (_price < finalCap) { return _price.mul(117).div(97); } else { return _price.mul(115).div(98); } } /** * @dev Purchase animal from previous owner * @param _tokenId uint256 of token */ function buyToken(uint256 _tokenId) public payable isNotContract(msg.sender) { // get data from storage Animal storage animal = arkData[_tokenId]; uint256 price = animal.price; address oldOwner = animal.owner; address newOwner = msg.sender; uint256 excess = msg.value.sub(price); // revert checks require(price > 0); require(msg.value >= price); require(oldOwner != msg.sender); require(oldOwner != address(0) && oldOwner != address(1)); // We're gonna put unbirthed babbies at 0x1 uint256 totalCut = price.mul(4).div(100); uint256 birtherCut = price.mul(animal.birtherPct).div(1000); // birtherPct is % * 10 so we / 1000 birtherBalances[animal.birther] = birtherBalances[animal.birther].add(birtherCut); uint256 devCut = totalCut.sub(birtherCut); developerCut = developerCut.add(devCut); transferToken(oldOwner, newOwner, _tokenId); // raise event Purchase(_tokenId, newOwner, oldOwner, price); // set new prices animal.price = getNextPrice(price); animal.lastPrice = price; // Transfer payment to old owner minus the developer's and birther's cut. oldOwner.transfer(price.sub(totalCut)); // Send refund to owner if needed if (excess > 0) { newOwner.transfer(excess); } checkBirth(_tokenId); } /** * @dev Check to see whether a newly purchased animal should give birth. * @param _tokenId Unique ID of the newly transferred animal. */ function checkBirth(uint256 _tokenId) internal { uint256 mom = 0; // gender 0 = male, 1 = female if (arkData[_tokenId].gender == 0) { mom = mates[_tokenId]; } else { mom = _tokenId; } if (babies[mom] > 0) { if (tokenOwner[mates[_tokenId]] == msg.sender) { // Check if the sum price to make a baby for these mates has been passed. uint256 sumPrice = arkData[_tokenId].lastPrice + arkData[mates[_tokenId]].lastPrice; if (sumPrice >= babyMakinPrice[babies[mom]]) { autoBirth(babies[mom]); Birth(msg.sender, mom, mates[mom], babies[mom]); babyMakinPrice[babies[mom]] = 0; babies[mom] = 0; mates[mates[mom]] = 0; mates[mom] = 0; } } } } /** * @dev Internal function to birth a baby if an owner has both mom and dad. * @param _baby Token ID of the baby to birth. */ function autoBirth(uint256 _baby) internal { Animal storage animal = arkData[_baby]; animal.birther = msg.sender; transferToken(animal.owner, msg.sender, _baby); } /** * @dev Transfer Token from Previous Owner to New Owner * @param _from previous owner address * @param _to new owner address * @param _tokenId uint256 ID of token */ function transferToken(address _from, address _to, uint256 _tokenId) internal { // check token exists require(tokenExists(_tokenId)); // make sure previous owner is correct require(arkData[_tokenId].owner == _from); require(_to != address(0)); require(_to != address(this)); // clear approvals linked to this token clearApproval(_from, _tokenId); // remove token from previous owner removeToken(_from, _tokenId); // update owner and add token to new owner addToken(_to, _tokenId); //raise event Transfer(_from, _to, _tokenId); } /** * @dev Withdraw dev's cut */ function withdraw(uint256 _amount) public onlyAdmin() { if (_amount == 0) { _amount = developerCut; } developerCut = developerCut.sub(_amount); owner.transfer(_amount); } /** * @dev Withdraw anyone's birther balance. * @param _beneficiary The person whose balance shall be sent to them. */ function withdrawBalance(address _beneficiary) external { uint256 payout = birtherBalances[_beneficiary]; birtherBalances[_beneficiary] = 0; _beneficiary.transfer(payout); } /** * @dev Return all relevant data for an animal. * @param _tokenId Unique animal ID. */ function getArkData (uint256 _tokenId) external view returns (address _owner, uint256 _price, uint256 _nextPrice, uint256 _mate, address _birther, uint8 _gender, uint256 _baby, uint256 _babyPrice) { Animal memory animal = arkData[_tokenId]; uint256 baby; if (animal.gender == 1) baby = babies[_tokenId]; else baby = babies[mates[_tokenId]]; return (animal.owner, animal.price, getNextPrice(animal.price), mates[_tokenId], animal.birther, animal.gender, baby, babyMakinPrice[baby]); } /** * @dev Get sum price required to birth baby. * @param _babyId Unique baby Id. */ function getBabyMakinPrice(uint256 _babyId) external view returns (uint256 price) { price = babyMakinPrice[_babyId]; } /** * @dev Get the parents of a certain baby. * @param _babyId Unique baby Id. */ function getBabyMommas(uint256 _babyId) external view returns (uint256[2] parents) { parents = babyMommas[_babyId]; } /** * @dev Frontend can use this to find the birther percent for animal. * @param _tokenId The unique id for the animal. */ function getBirthCut(uint256 _tokenId) external view returns (uint256 birthCut) { birthCut = arkData[_tokenId].birtherPct; } /** * @dev Check the birther balance of a certain address. * @param _owner The address to check the balance of. */ function checkBalance(address _owner) external view returns (uint256) { return birtherBalances[_owner]; } /** * @dev Determines if token exists by checking it's price * @param _tokenId uint256 ID of token */ function tokenExists (uint256 _tokenId) public view returns (bool _exists) { return arkData[_tokenId].price > 0; } /** * @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 Guarantees msg.sender is not a contract * @param _buyer address of person buying animal */ modifier isNotContract(address _buyer) { uint size; assembly { size := extcodesize(_buyer) } require(size == 0); _; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { return ownedTokens[_owner].length; } /** * @dev Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; return owner; } /** * @dev Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function approvedFor(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @dev Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (approvedFor(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) public { require(isApprovedFor(msg.sender, _tokenId)); clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @dev Tells whether the msg.sender is approved for the given token ID or not * This function is not private so it can be extended in further implementations like the operatable ERC721 * @param _owner address of the owner to query the approval of * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) { return approvedFor(_tokenId) == _owner; } /** * @dev Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal isNotContract(_to) { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); clearApproval(_from, _tokenId); removeToken(_from, _tokenId); addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @dev Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; arkData[_tokenId].owner = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } function name() public pure returns (string _name) { return "EthersArk Token"; } function symbol() public pure returns (string _symbol) { return "EARK"; } }
We're gonna put unbirthed babbies at 0x1
require(oldOwner != address(0) && oldOwner != address(1));
1,146,735
[ 1, 3218, 4565, 314, 265, 6582, 1378, 640, 22531, 329, 324, 19364, 606, 622, 374, 92, 21, 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, 2583, 12, 1673, 5541, 480, 1758, 12, 20, 13, 597, 1592, 5541, 480, 1758, 12, 21, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../StakingRewardsWithFarming.sol"; import "../../Constants.sol"; import "../../interface/IMasterchef.sol"; contract StakingRewardsWithFarmingSushi is StakingRewardsWithFarming { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public poolId; address public masterchef = Constants.SUSHI_MASTERCHEF; constructor( uint256 _poolId, address _owner, address _yieldRecipient, address _rewardsToken, address _stakingToken, address[] memory _nonRecoverableTokens ) StakingRewardsWithFarming(_owner, _yieldRecipient, _rewardsToken, _stakingToken, _nonRecoverableTokens) { poolId = _poolId; } // How much have we deposited into the farm function getDepositedToFarm() public view override returns (uint256) { (uint256 amount, ) = IMasterchef(masterchef).userInfo(poolId, address(this)); return amount; } // How much can we harvest from the farm // Use `eth_call` on this function getHarvestableFromFarm() public view returns (uint256) { return IMasterchef(masterchef).pendingSushi(poolId, address(this)); } // Deposits tokens into the farm function depositToFarm() public override { uint256 _depositable = getDepositableToFarm(); if (_depositable > 0) { stakingToken.safeApprove(masterchef, 0); stakingToken.safeApprove(masterchef, _depositable); IMasterchef(masterchef).deposit(poolId, _depositable); } } // Withdraws _amount from the farm function withdrawFromFarm(uint256 _amount) public override { IMasterchef(masterchef).withdraw(poolId, _amount); } }
How much have we deposited into the farm
function getDepositedToFarm() public view override returns (uint256) { (uint256 amount, ) = IMasterchef(masterchef).userInfo(poolId, address(this)); return amount; }
12,739,930
[ 1, 44, 543, 9816, 1240, 732, 443, 1724, 329, 1368, 326, 284, 4610, 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, 565, 445, 336, 758, 1724, 329, 774, 42, 4610, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 11890, 5034, 3844, 16, 262, 273, 6246, 2440, 343, 10241, 12, 7525, 343, 10241, 2934, 1355, 966, 12, 6011, 548, 16, 1758, 12, 2211, 10019, 203, 3639, 327, 3844, 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/0x92B30E2b504C4AfBbf518db8c74DE5cDfBEd369d/sources/BadgerGeyser.sol
* @return The token users receive as they unstake./
function getDistributionTokens() public view returns (address[] memory) { uint256 numTokens = distributionTokens.length(); address[] memory tokens = new address[](numTokens); for (uint256 i = 0; i < numTokens; i++) { tokens[i] = distributionTokens.at(i); } return tokens; }
3,725,500
[ 1, 2463, 1021, 1147, 3677, 6798, 487, 2898, 640, 334, 911, 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, 565, 445, 336, 9003, 5157, 1435, 1071, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 818, 5157, 273, 7006, 5157, 18, 2469, 5621, 203, 3639, 1758, 8526, 3778, 2430, 273, 394, 1758, 8526, 12, 2107, 5157, 1769, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 203, 5411, 2430, 63, 77, 65, 273, 7006, 5157, 18, 270, 12, 77, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2430, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.11; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; /// @title Bet factory contract. /// @author Fermin Carranza /// @notice Bet contract. Only ETH/USD currently supported. contract Bet { /// Events - Publicize events to listeners. event LogUserPlacedBet(address _address, SideOfBet _side); event LogUserCancelledBet(address _address, SideOfBet _side); event LogPayoutToUser(address _payout, uint _amount); enum SideOfBet { OVER, UNDER, NONE } /// Chainlink price feed AggregatorV3Interface internal priceFeed; /// Structure that represents a placed bet by a user. struct PlacedBet { address bettor; SideOfBet side; uint betSize; bool isBetting; } /// Storage variables. address payable public owner = payable(msg.sender); bool public isLive = true; string public symbol; int public line; int public spread; int public maxBetSize; uint public expiration; int public payoutMultiplier; // Divide by 10 for float mapping (address => PlacedBet) public betsByUser; uint8 public numberOfBets = 0; uint public contractBalance; address[] public usersBetting; constructor(string memory _symbol, int _line, int _spread, int _maxBetSize, int _multiplier, uint _expiration) { symbol = _symbol; line = _line * 10**18; spread = _spread * 10**18; maxBetSize = _maxBetSize * 10**18; payoutMultiplier = _multiplier; expiration = _expiration; priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); // Rinkeby: 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e // Kovan: 0x9326BFA02ADD2366b30bacB125260Af641031331 } /// @notice Cancel an existing bet. /// @dev Only one bet per user currently supported. function cancelBet() public { require(betsByUser[msg.sender].isBetting == true, "User has no bet to cancel."); PlacedBet storage existingBet = betsByUser[msg.sender]; uint valueToReturn = existingBet.betSize; require(contractBalance >= valueToReturn, "You are trying to withdraw too much Ether."); existingBet.isBetting = false; existingBet.betSize = 0; existingBet.side = SideOfBet.NONE; numberOfBets -= 1; contractBalance -= valueToReturn; removeFromUsersBetting(msg.sender); (bool sent,) = existingBet.bettor.call{value: valueToReturn}(""); require(sent, "Failed to return Ether"); emit LogUserPlacedBet(msg.sender, existingBet.side); } /// @notice Place a new bet. /// @dev Only one bet per user currently supported. /// @param _side The side to take on the bet (over/under). function placeBet(string memory _side) public payable { require(msg.sender != owner, "Creator cannot place bet."); require(betsByUser[msg.sender].isBetting == false, "User already has placed a bet."); SideOfBet sideTaken = getSideOfBetFromString(_side); usersBetting.push(msg.sender); PlacedBet memory newBet = PlacedBet({ bettor: msg.sender, side: sideTaken, betSize: msg.value, isBetting: true }); betsByUser[msg.sender] = newBet; numberOfBets += 1; contractBalance += msg.value; emit LogUserPlacedBet(msg.sender, sideTaken); } /// @notice List all users currently betting on this contract. /// @return Returns an array of addresses. function getAllUsersBetting() public view returns (address[] memory) { return usersBetting; } /// @notice Returns bet's details. /// @return Array containing: symbol, line, spread and expiration of bet. function getBetDetails() public view returns (string memory, int, int, uint, address) { return (symbol, line, spread, expiration, address(this)); } /// @notice Utility method to return the enum value for side of bet taken. /// @dev Internal only. /// @return sideOfBet Side of bet taken. function getSideOfBetFromString(string memory _side) internal pure returns (SideOfBet sideOfBet) { if (keccak256(abi.encodePacked((_side))) == keccak256(abi.encodePacked(("over")))) { return SideOfBet.OVER; } else if (keccak256(abi.encodePacked((_side))) == keccak256(abi.encodePacked(("under")))) { return SideOfBet.UNDER; } require(false, "Side of bet must be either: 'over' or 'under'."); } /// @notice Returns current price of security (currently only supports ETH/USD). /// @dev Chainlink price feed. /// @return int Returns integer value of security price. function getCurrentPrice() public view returns (int) { (, int price, , , ) = priceFeed.latestRoundData(); return price; // return 3500; // Test number } /// @notice Send funds to parent contract and self destruct. function kill(uint _outstandingBets) public { require(_outstandingBets == 0, "Contract still has unresolved bets"); (bool success, ) = owner.call{value: contractBalance}(""); require(success, "Failed to send Ether"); selfdestruct(owner); } /// @notice Resolves an outstanding bet contract at expiration. If winner, send corresponding funds. function resolveBet() public { require(msg.sender == owner, "Only contract owner can resolve bet."); int currentPrice = getCurrentPrice() * (10**10); SideOfBet winningSide = SideOfBet.NONE; if (currentPrice > line + spread) { winningSide = SideOfBet.OVER; } else if (currentPrice < line - spread) { winningSide = SideOfBet.UNDER; } uint outstandingBets = numberOfBets; for (uint8 i = 0; i < numberOfBets; i++) { address userAddress = usersBetting[i]; PlacedBet storage bet = betsByUser[userAddress]; if (bet.isBetting && bet.side == winningSide) { payout(userAddress, bet.betSize); } outstandingBets--; } kill(outstandingBets); } /// @notice Send funds to winners of bet. function payout(address _bettor, uint _betSize) internal { uint toWithdraw = uint(_betSize) * uint(payoutMultiplier) / 10; require(contractBalance >= toWithdraw, "Insufficient funds to withdraw."); contractBalance -= toWithdraw; (bool success, ) = _bettor.call{value: toWithdraw}(""); string memory failMessage = string( abi.encodePacked("Failed to send Ether to bet winner with address: ", _bettor) ); require(success, failMessage); emit LogPayoutToUser(_bettor, toWithdraw); } /// @notice Removes a user from current bettors if user cancels. /// @dev Convenience method to remove from array. function removeFromUsersBetting(address _address) internal { uint256 index; for (uint i = 0; i < usersBetting.length; i++) { if (usersBetting[i] == _address) { index = i; } } usersBetting[index] = usersBetting[usersBetting.length - 1]; usersBetting.pop(); } }
@notice Place a new bet. @dev Only one bet per user currently supported. @param _side The side to take on the bet (over/under).
function placeBet(string memory _side) public payable { require(msg.sender != owner, "Creator cannot place bet."); require(betsByUser[msg.sender].isBetting == false, "User already has placed a bet."); SideOfBet sideTaken = getSideOfBetFromString(_side); usersBetting.push(msg.sender); PlacedBet memory newBet = PlacedBet({ bettor: msg.sender, side: sideTaken, betSize: msg.value, isBetting: true }); betsByUser[msg.sender] = newBet; numberOfBets += 1; contractBalance += msg.value; emit LogUserPlacedBet(msg.sender, sideTaken); }
15,796,917
[ 1, 6029, 279, 394, 2701, 18, 225, 5098, 1245, 2701, 1534, 729, 4551, 3260, 18, 225, 389, 5564, 1021, 4889, 358, 4862, 603, 326, 2701, 261, 1643, 19, 9341, 2934, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3166, 38, 278, 12, 1080, 3778, 389, 5564, 13, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 480, 3410, 16, 315, 10636, 2780, 3166, 2701, 1199, 1769, 203, 3639, 2583, 12, 70, 2413, 25895, 63, 3576, 18, 15330, 8009, 291, 38, 278, 1787, 422, 629, 16, 315, 1299, 1818, 711, 15235, 279, 2701, 1199, 1769, 203, 3639, 26248, 951, 38, 278, 4889, 27486, 273, 1322, 831, 951, 38, 278, 9193, 24899, 5564, 1769, 203, 3639, 3677, 38, 278, 1787, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 3639, 13022, 72, 38, 278, 3778, 394, 38, 278, 273, 13022, 72, 38, 278, 12590, 203, 5411, 2701, 13039, 30, 1234, 18, 15330, 16, 203, 5411, 4889, 30, 4889, 27486, 16, 203, 5411, 2701, 1225, 30, 1234, 18, 1132, 16, 203, 5411, 27057, 278, 1787, 30, 638, 203, 3639, 15549, 203, 203, 3639, 324, 2413, 25895, 63, 3576, 18, 15330, 65, 273, 394, 38, 278, 31, 203, 3639, 7922, 38, 2413, 1011, 404, 31, 203, 3639, 6835, 13937, 1011, 1234, 18, 1132, 31, 203, 203, 3639, 3626, 1827, 1299, 6029, 72, 38, 278, 12, 3576, 18, 15330, 16, 4889, 27486, 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 ]
{"BlubStakingV3.sol":{"content":"// SPDX-License-Identifier: MIT\r\npragma solidity \u003e= 0.8.7;\r\n\r\nimport \"./Ownable.sol\";\r\nimport \"./ECDSA.sol\";\r\nimport \"./Strings.sol\";\r\nimport \"./IERC721.sol\";\r\n\r\ninterface IBlubToken {\r\n function mintAdminContract(address account, uint256 amount) external;\r\n}\r\n\r\ncontract BlubStaking is Ownable {\r\n using ECDSA for bytes32;\r\n using Strings for uint256;\r\n\r\n // contract params\r\n address public deployer;\r\n IBlubToken public blubToken;\r\n\r\n // map to store which nonce has been used onchain\r\n mapping(uint256 =\u003e bool) public nonceIsUsed;\r\n\r\n // event to track which nonces have been used\r\n event Claimed(uint256 indexed nonce);\r\n\r\n uint256 public constant CLAIM_TIME_WINDOW = 1200; // 60*20\r\n\r\n /**\r\n * @dev Initializes the contract by setting blubToken\r\n */\r\n constructor(address blubTokenAddress, address deployerAddress) {\r\n blubToken = IBlubToken(blubTokenAddress);\r\n deployer = deployerAddress;\r\n }\r\n \r\n /**\r\n * @dev Sets contract parameters\r\n */\r\n function setParams(address blubTokenAddress, address deployerAddress) public onlyOwner {\r\n blubToken = IBlubToken(blubTokenAddress);\r\n deployer = deployerAddress;\r\n }\r\n\r\n /**\r\n * @dev Claim BLUB token accrued through virtual staking for multiple tokens\r\n */\r\n function claim(uint256 nonce, uint256 amount, uint256 timestamp, bytes calldata signature) public {\r\n string memory message = string(abi.encodePacked(\"|\", Strings.toHexString(uint256(uint160(msg.sender)), 20), \"|\", nonce.toString(), \"|\", amount.toString(), \"|\", timestamp.toString()));\r\n bytes32 hashedMessage = keccak256(abi.encodePacked(message));\r\n address recoveredAddress = keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hashedMessage)).recover(signature);\r\n require(recoveredAddress == deployer, \"Unauthorized signature\");\r\n\r\n require(nonceIsUsed[nonce] == false, \"Replayed tx\");\r\n nonceIsUsed[nonce] = true;\r\n\r\n require(block.timestamp \u003c timestamp + CLAIM_TIME_WINDOW, \"Claim too late\");\r\n\r\n blubToken.mintAdminContract(msg.sender, amount);\r\n emit Claimed(nonce);\r\n }\r\n}"},"Context.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (utils/Context.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Provides information about the current execution context, including the\r\n * sender of the transaction and its data. While these are generally available\r\n * via msg.sender and msg.data, they should not be accessed in such a direct\r\n * manner, since when dealing with meta-transactions the account sending and\r\n * paying for execution may not be the actual sender (as far as an application\r\n * is concerned).\r\n *\r\n * This contract is only required for intermediate, library-like contracts.\r\n */\r\nabstract contract Context {\r\n function _msgSender() internal view virtual returns (address) {\r\n return msg.sender;\r\n }\r\n\r\n function _msgData() internal view virtual returns (bytes calldata) {\r\n return msg.data;\r\n }\r\n}\r\n"},"ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (utils/cryptography/ECDSA.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Strings.sol\";\r\n\r\n/**\r\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\r\n *\r\n * These functions can be used to verify that a message was signed by the holder\r\n * of the private keys of a given address.\r\n */\r\nlibrary ECDSA {\r\n enum RecoverError {\r\n NoError,\r\n InvalidSignature,\r\n InvalidSignatureLength,\r\n InvalidSignatureS,\r\n InvalidSignatureV\r\n }\r\n\r\n function _throwError(RecoverError error) private pure {\r\n if (error == RecoverError.NoError) {\r\n return; // no error: do nothing\r\n } else if (error == RecoverError.InvalidSignature) {\r\n revert(\"ECDSA: invalid signature\");\r\n } else if (error == RecoverError.InvalidSignatureLength) {\r\n revert(\"ECDSA: invalid signature length\");\r\n } else if (error == RecoverError.InvalidSignatureS) {\r\n revert(\"ECDSA: invalid signature \u0027s\u0027 value\");\r\n } else if (error == RecoverError.InvalidSignatureV) {\r\n revert(\"ECDSA: invalid signature \u0027v\u0027 value\");\r\n }\r\n }\r\n\r\n /**\r\n * @dev Returns the address that signed a hashed message (`hash`) with\r\n * `signature` or error string. This address can then be used for verification purposes.\r\n *\r\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\r\n * this function rejects them by requiring the `s` value to be in the lower\r\n * half order, and the `v` value to be either 27 or 28.\r\n *\r\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\r\n * verification to be secure: it is possible to craft signatures that\r\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\r\n * this is by receiving a hash of the original message (which may otherwise\r\n * be too long), and then calling {toEthSignedMessageHash} on it.\r\n *\r\n * Documentation for signature generation:\r\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\r\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\r\n // Check the signature length\r\n // - case 65: r,s,v signature (standard)\r\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\r\n if (signature.length == 65) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n // ecrecover takes the signature parameters, and the only way to get them\r\n // currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n s := mload(add(signature, 0x40))\r\n v := byte(0, mload(add(signature, 0x60)))\r\n }\r\n return tryRecover(hash, v, r, s);\r\n } else if (signature.length == 64) {\r\n bytes32 r;\r\n bytes32 vs;\r\n // ecrecover takes the signature parameters, and the only way to get them\r\n // currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n vs := mload(add(signature, 0x40))\r\n }\r\n return tryRecover(hash, r, vs);\r\n } else {\r\n return (address(0), RecoverError.InvalidSignatureLength);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Returns the address that signed a hashed message (`hash`) with\r\n * `signature`. This address can then be used for verification purposes.\r\n *\r\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\r\n * this function rejects them by requiring the `s` value to be in the lower\r\n * half order, and the `v` value to be either 27 or 28.\r\n *\r\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\r\n * verification to be secure: it is possible to craft signatures that\r\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\r\n * this is by receiving a hash of the original message (which may otherwise\r\n * be too long), and then calling {toEthSignedMessageHash} on it.\r\n */\r\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, signature);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\r\n *\r\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address, RecoverError) {\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\r\n v := add(shr(255, vs), 27)\r\n }\r\n return tryRecover(hash, v, r, s);\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\r\n *\r\n * _Available since v4.2._\r\n */\r\n function recover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\r\n * `r` and `s` signature fields separately.\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(\r\n bytes32 hash,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) internal pure returns (address, RecoverError) {\r\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\r\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\r\n // the valid range for s in (301): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\r\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\r\n //\r\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\r\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\r\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\r\n // these malleable signatures as well.\r\n if (uint256(s) \u003e 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\r\n return (address(0), RecoverError.InvalidSignatureS);\r\n }\r\n if (v != 27 \u0026\u0026 v != 28) {\r\n return (address(0), RecoverError.InvalidSignatureV);\r\n }\r\n\r\n // If the signature is valid (and not malleable), return the signer address\r\n address signer = ecrecover(hash, v, r, s);\r\n if (signer == address(0)) {\r\n return (address(0), RecoverError.InvalidSignature);\r\n }\r\n\r\n return (signer, RecoverError.NoError);\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-recover} that receives the `v`,\r\n * `r` and `s` signature fields separately.\r\n */\r\n function recover(\r\n bytes32 hash,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\r\n * produces hash corresponding to the one signed with the\r\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\r\n * JSON-RPC method as part of EIP-191.\r\n *\r\n * See {recover}.\r\n */\r\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\r\n // 32 is the length in bytes of hash,\r\n // enforced by the type signature above\r\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Message, created from `s`. This\r\n * produces hash corresponding to the one signed with the\r\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\r\n * JSON-RPC method as part of EIP-191.\r\n *\r\n * See {recover}.\r\n */\r\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\r\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Typed Data, created from a\r\n * `domainSeparator` and a `structHash`. This produces hash corresponding\r\n * to the one signed with the\r\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\r\n * JSON-RPC method as part of EIP-712.\r\n *\r\n * See {recover}.\r\n */\r\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\r\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\r\n }\r\n}\r\n"},"IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (utils/introspection/IERC165.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Interface of the ERC165 standard, as defined in the\r\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\r\n *\r\n * Implementers can declare support of contract interfaces, which can then be\r\n * queried by others ({ERC165Checker}).\r\n *\r\n * For an implementation, see {ERC165}.\r\n */\r\ninterface IERC165 {\r\n /**\r\n * @dev Returns true if this contract implements the interface defined by\r\n * `interfaceId`. See the corresponding\r\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\r\n * to learn more about how these ids are created.\r\n *\r\n * This function call must use less than 30 000 gas.\r\n */\r\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\r\n}\r\n"},"IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./IERC165.sol\";\r\n\r\n/**\r\n * @dev Required interface of an ERC721 compliant contract.\r\n */\r\ninterface IERC721 is IERC165 {\r\n /**\r\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\r\n */\r\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\r\n\r\n /**\r\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\r\n */\r\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\r\n\r\n /**\r\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\r\n */\r\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\r\n\r\n /**\r\n * @dev Returns the number of tokens in ``owner``\u0027s account.\r\n */\r\n function balanceOf(address owner) external view returns (uint256 balance);\r\n\r\n /**\r\n * @dev Returns the owner of the `tokenId` token.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */\r\n function ownerOf(uint256 tokenId) external view returns (address owner);\r\n\r\n /**\r\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\r\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must exist and be owned by `from`.\r\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) external;\r\n\r\n /**\r\n * @dev Transfers `tokenId` token from `from` to `to`.\r\n *\r\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must be owned by `from`.\r\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function transferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) external;\r\n\r\n /**\r\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\r\n * The approval is cleared when the token is transferred.\r\n *\r\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\r\n *\r\n * Requirements:\r\n *\r\n * - The caller must own the token or be an approved operator.\r\n * - `tokenId` must exist.\r\n *\r\n * Emits an {Approval} event.\r\n */\r\n function approve(address to, uint256 tokenId) external;\r\n\r\n /**\r\n * @dev Returns the account approved for `tokenId` token.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */\r\n function getApproved(uint256 tokenId) external view returns (address operator);\r\n\r\n /**\r\n * @dev Approve or remove `operator` as an operator for the caller.\r\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\r\n *\r\n * Requirements:\r\n *\r\n * - The `operator` cannot be the caller.\r\n *\r\n * Emits an {ApprovalForAll} event.\r\n */\r\n function setApprovalForAll(address operator, bool _approved) external;\r\n\r\n /**\r\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\r\n *\r\n * See {setApprovalForAll}\r\n */\r\n function isApprovedForAll(address owner, address operator) external view returns (bool);\r\n\r\n /**\r\n * @dev Safely transfers `tokenId` token from `from` to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must exist and be owned by `from`.\r\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId,\r\n bytes calldata data\r\n ) external;\r\n}\r\n"},"Ownable.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (access/Ownable.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Context.sol\";\r\n\r\n/**\r\n * @dev Contract module which provides a basic access control mechanism, where\r\n * there is an account (an owner) that can be granted exclusive access to\r\n * specific functions.\r\n *\r\n * By default, the owner account will be the one that deploys the contract. This\r\n * can later be changed with {transferOwnership}.\r\n *\r\n * This module is used through inheritance. It will make available the modifier\r\n * `onlyOwner`, which can be applied to your functions to restrict their use to\r\n * the owner.\r\n */\r\nabstract contract Ownable is Context {\r\n address private _owner;\r\n\r\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\r\n\r\n /**\r\n * @dev Initializes the contract setting the deployer as the initial owner.\r\n */\r\n constructor() {\r\n _transferOwnership(_msgSender());\r\n }\r\n\r\n /**\r\n * @dev Returns the address of the current owner.\r\n */\r\n function owner() public view virtual returns (address) {\r\n return _owner;\r\n }\r\n\r\n /**\r\n * @dev Throws if called by any account other than the owner.\r\n */\r\n modifier onlyOwner() {\r\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\r\n _;\r\n }\r\n\r\n /**\r\n * @dev Leaves the contract without owner. It will not be possible to call\r\n * `onlyOwner` functions anymore. Can only be called by the current owner.\r\n *\r\n * NOTE: Renouncing ownership will leave the contract without an owner,\r\n * thereby removing any functionality that is only available to the owner.\r\n */\r\n function renounceOwnership() public virtual onlyOwner {\r\n _transferOwnership(address(0));\r\n }\r\n\r\n /**\r\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\r\n * Can only be called by the current owner.\r\n */\r\n function transferOwnership(address newOwner) public virtual onlyOwner {\r\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\r\n _transferOwnership(newOwner);\r\n }\r\n\r\n /**\r\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\r\n * Internal function without access restriction.\r\n */\r\n function _transferOwnership(address newOwner) internal virtual {\r\n address oldOwner = _owner;\r\n _owner = newOwner;\r\n emit OwnershipTransferred(oldOwner, newOwner);\r\n }\r\n}\r\n"},"Strings.sol":{"content":"// SPDX-License-Identifier: MIT\r\n// OpenZeppelin Contracts v4.3.2 (utils/Strings.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev String operations.\r\n */\r\nlibrary Strings {\r\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\r\n */\r\n function toString(uint256 value) internal pure returns (string memory) {\r\n // Inspired by OraclizeAPI\u0027s implementation - MIT licence\r\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\r\n */\r\n function toHexString(uint256 value) internal pure returns (string memory) {\r\n if (value == 0) {\r\n return \"0x00\";\r\n }\r\n uint256 temp = value;\r\n uint256 length = 0;\r\n while (temp != 0) {\r\n length++;\r\n temp \u003e\u003e= 8;\r\n }\r\n return toHexString(value, length);\r\n }\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\r\n */\r\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\r\n bytes memory buffer = new bytes(2 * length + 2);\r\n buffer[0] = \"0\";\r\n buffer[1] = \"x\";\r\n for (uint256 i = 2 * length + 1; i \u003e 1; --i) {\r\n buffer[i] = _HEX_SYMBOLS[value \u0026 0xf];\r\n value \u003e\u003e= 4;\r\n }\r\n require(value == 0, \"Strings: hex length insufficient\");\r\n return string(buffer);\r\n }\r\n}\r\n"}}
SPDX-License-Identifier: MIT\r\npragma solidity \u003e= 0.8.7;\r\n\r\nimport \"./Ownable.sol\";\r\nimport \"./ECDSA.sol\";\r\nimport \"./Strings.sol\";\r\nimport \"./IERC721.sol\";\r\n\r\ninterface IBlubToken {\r\n function mintAdminContract(address account, uint256 amount) external;\r\n}\r\n\r\ncontract BlubStaking is Ownable {\r\n using ECDSA for bytes32;\r\n using Strings for uint256;\r\n\r\n contract params\r\n address public deployer;\r\n IBlubToken public blubToken;\r\n\r\n map to store which nonce has been used onchain\r\n mapping(uint256 =\u003e bool) public nonceIsUsed;\r\n\r\n event to track which nonces have been used\r\n event Claimed(uint256 indexed nonce);\r\n\r\n uint256 public constant CLAIM_TIME_WINDOW = 1200; 60*20\r\n\r\n /**\r\n * @dev Initializes the contract by setting blubToken\r\n */\r\n constructor(address blubTokenAddress, address deployerAddress) {\r\n blubToken = IBlubToken(blubTokenAddress);\r\n deployer = deployerAddress;\r\n }\r\n \r\n /**\r\n * @dev Sets contract parameters\r\n */\r\n function setParams(address blubTokenAddress, address deployerAddress) public onlyOwner {\r\n blubToken = IBlubToken(blubTokenAddress);\r\n deployer = deployerAddress;\r\n }\r\n\r\n /**\r\n * @dev Claim BLUB token accrued through virtual staking for multiple tokens\r\n */\r\n function claim(uint256 nonce, uint256 amount, uint256 timestamp, bytes calldata signature) public {\r\n string memory message = string(abi.encodePacked(\"|\", Strings.toHexString(uint256(uint160(msg.sender)), 20), \"|\", nonce.toString(), \"|\", amount.toString(), \"|\", timestamp.toString()));\r\n bytes32 hashedMessage = keccak256(abi.encodePacked(message));\r\n address recoveredAddress = keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hashedMessage)).recover(signature);\r\n require(recoveredAddress == deployer, \"Unauthorized signature\");\r\n\r\n require(nonceIsUsed[nonce] == false, \"Replayed tx\");\r\n nonceIsUsed[nonce] = true;\r\n\r\n require(block.timestamp \u003c timestamp + CLAIM_TIME_WINDOW, \"Claim too late\");\r\n\r\n blubToken.mintAdminContract(msg.sender, amount);\r\n emit Claimed(nonce);\r\n }\r\n}"},"Context.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (utils/Context.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Provides information about the current execution context, including the\r\n * sender of the transaction and its data. While these are generally available\r\n * via msg.sender and msg.data, they should not be accessed in such a direct\r\n * manner, since when dealing with meta-transactions the account sending and\r\n * paying for execution may not be the actual sender (as far as an application\r\n * is concerned).\r\n *\r\n * This contract is only required for intermediate, library-like contracts.\r\n */\r\nabstract contract Context {\r\n function _msgSender() internal view virtual returns (address) {\r\n return msg.sender;\r\n }\r\n\r\n function _msgData() internal view virtual returns (bytes calldata) {\r\n return msg.data;\r\n }\r\n}\r\n"},"ECDSA.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (utils/cryptography/ECDSA.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Strings.sol\";\r\n\r\n/**\r\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\r\n *\r\n * These functions can be used to verify that a message was signed by the holder\r\n * of the private keys of a given address.\r\n */\r\nlibrary ECDSA {\r\n enum RecoverError {\r\n NoError,\r\n InvalidSignature,\r\n InvalidSignatureLength,\r\n InvalidSignatureS,\r\n InvalidSignatureV\r\n }\r\n\r\n function _throwError(RecoverError error) private pure {\r\n if (error == RecoverError.NoError) {\r\n return; no error: do nothing\r\n } else if (error == RecoverError.InvalidSignature) {\r\n revert(\"ECDSA: invalid signature\");\r\n } else if (error == RecoverError.InvalidSignatureLength) {\r\n revert(\"ECDSA: invalid signature length\");\r\n } else if (error == RecoverError.InvalidSignatureS) {\r\n revert(\"ECDSA: invalid signature \u0027s\u0027 value\");\r\n } else if (error == RecoverError.InvalidSignatureV) {\r\n revert(\"ECDSA: invalid signature \u0027v\u0027 value\");\r\n }\r\n }\r\n\r\n /**\r\n * @dev Returns the address that signed a hashed message (`hash`) with\r\n * `signature` or error string. This address can then be used for verification purposes.\r\n *\r\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\r\n * this function rejects them by requiring the `s` value to be in the lower\r\n * half order, and the `v` value to be either 27 or 28.\r\n *\r\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\r\n * verification to be secure: it is possible to craft signatures that\r\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\r\n * this is by receiving a hash of the original message (which may otherwise\r\n * be too long), and then calling {toEthSignedMessageHash} on it.\r\n *\r\n * Documentation for signature generation:\r\n * - with https:web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\r\n * - with https:docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\r\n Check the signature length\r\n - case 65: r,s,v signature (standard)\r\n - case 64: r,vs signature (cf https:eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\r\n if (signature.length == 65) {\r\n bytes32 r;\r\n bytes32 s;\r\n uint8 v;\r\n ecrecover takes the signature parameters, and the only way to get them\r\n currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n s := mload(add(signature, 0x40))\r\n v := byte(0, mload(add(signature, 0x60)))\r\n }\r\n return tryRecover(hash, v, r, s);\r\n } else if (signature.length == 64) {\r\n bytes32 r;\r\n bytes32 vs;\r\n ecrecover takes the signature parameters, and the only way to get them\r\n currently is to use assembly.\r\n assembly {\r\n r := mload(add(signature, 0x20))\r\n vs := mload(add(signature, 0x40))\r\n }\r\n return tryRecover(hash, r, vs);\r\n } else {\r\n return (address(0), RecoverError.InvalidSignatureLength);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Returns the address that signed a hashed message (`hash`) with\r\n * `signature`. This address can then be used for verification purposes.\r\n *\r\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\r\n * this function rejects them by requiring the `s` value to be in the lower\r\n * half order, and the `v` value to be either 27 or 28.\r\n *\r\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\r\n * verification to be secure: it is possible to craft signatures that\r\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\r\n * this is by receiving a hash of the original message (which may otherwise\r\n * be too long), and then calling {toEthSignedMessageHash} on it.\r\n */\r\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, signature);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\r\n *\r\n * See https:eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address, RecoverError) {\r\n bytes32 s;\r\n uint8 v;\r\n assembly {\r\n s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)\r\n v := add(shr(255, vs), 27)\r\n }\r\n return tryRecover(hash, v, r, s);\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\r\n *\r\n * _Available since v4.2._\r\n */\r\n function recover(\r\n bytes32 hash,\r\n bytes32 r,\r\n bytes32 vs\r\n ) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\r\n * `r` and `s` signature fields separately.\r\n *\r\n * _Available since v4.3._\r\n */\r\n function tryRecover(\r\n bytes32 hash,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) internal pure returns (address, RecoverError) {\r\n EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\r\n unique. Appendix F in the Ethereum Yellow paper (https:ethereum.github.io/yellowpaper/paper.pdf), defines\r\n the valid range for s in (301): 0 \u003c s \u003c secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\r\n signatures from current libraries generate a unique signature with an s-value in the lower half order.\r\n \r\n If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\r\n with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\r\n vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\r\n these malleable signatures as well.\r\n if (uint256(s) \u003e 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\r\n return (address(0), RecoverError.InvalidSignatureS);\r\n }\r\n if (v != 27 \u0026\u0026 v != 28) {\r\n return (address(0), RecoverError.InvalidSignatureV);\r\n }\r\n\r\n If the signature is valid (and not malleable), return the signer address\r\n address signer = ecrecover(hash, v, r, s);\r\n if (signer == address(0)) {\r\n return (address(0), RecoverError.InvalidSignature);\r\n }\r\n\r\n return (signer, RecoverError.NoError);\r\n }\r\n\r\n /**\r\n * @dev Overload of {ECDSA-recover} that receives the `v`,\r\n * `r` and `s` signature fields separately.\r\n */\r\n function recover(\r\n bytes32 hash,\r\n uint8 v,\r\n bytes32 r,\r\n bytes32 s\r\n ) internal pure returns (address) {\r\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\r\n _throwError(error);\r\n return recovered;\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\r\n * produces hash corresponding to the one signed with the\r\n * https:eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\r\n * JSON-RPC method as part of EIP-191.\r\n *\r\n * See {recover}.\r\n */\r\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\r\n 32 is the length in bytes of hash,\r\n enforced by the type signature above\r\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Message, created from `s`. This\r\n * produces hash corresponding to the one signed with the\r\n * https:eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\r\n * JSON-RPC method as part of EIP-191.\r\n *\r\n * See {recover}.\r\n */\r\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\r\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\r\n }\r\n\r\n /**\r\n * @dev Returns an Ethereum Signed Typed Data, created from a\r\n * `domainSeparator` and a `structHash`. This produces hash corresponding\r\n * to the one signed with the\r\n * https:eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\r\n * JSON-RPC method as part of EIP-712.\r\n *\r\n * See {recover}.\r\n */\r\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\r\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\r\n }\r\n}\r\n"},"IERC165.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (utils/introspection/IERC165.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev Interface of the ERC165 standard, as defined in the\r\n * https:eips.ethereum.org/EIPS/eip-165[EIP].\r\n *\r\n * Implementers can declare support of contract interfaces, which can then be\r\n * queried by others ({ERC165Checker}).\r\n *\r\n * For an implementation, see {ERC165}.\r\n */\r\ninterface IERC165 {\r\n /**\r\n * @dev Returns true if this contract implements the interface defined by\r\n * `interfaceId`. See the corresponding\r\n * https:eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\r\n * to learn more about how these ids are created.\r\n *\r\n * This function call must use less than 30 000 gas.\r\n */\r\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\r\n}\r\n"},"IERC721.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (token/ERC721/IERC721.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./IERC165.sol\";\r\n\r\n/**\r\n * @dev Required interface of an ERC721 compliant contract.\r\n */\r\ninterface IERC721 is IERC165 {\r\n /**\r\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\r\n */\r\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\r\n\r\n /**\r\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\r\n */\r\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\r\n\r\n /**\r\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\r\n */\r\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\r\n\r\n /**\r\n * @dev Returns the number of tokens in ``owner``\u0027s account.\r\n */\r\n function balanceOf(address owner) external view returns (uint256 balance);\r\n\r\n /**\r\n * @dev Returns the owner of the `tokenId` token.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */\r\n function ownerOf(uint256 tokenId) external view returns (address owner);\r\n\r\n /**\r\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\r\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must exist and be owned by `from`.\r\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) external;\r\n\r\n /**\r\n * @dev Transfers `tokenId` token from `from` to `to`.\r\n *\r\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must be owned by `from`.\r\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function transferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId\r\n ) external;\r\n\r\n /**\r\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\r\n * The approval is cleared when the token is transferred.\r\n *\r\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\r\n *\r\n * Requirements:\r\n *\r\n * - The caller must own the token or be an approved operator.\r\n * - `tokenId` must exist.\r\n *\r\n * Emits an {Approval} event.\r\n */\r\n function approve(address to, uint256 tokenId) external;\r\n\r\n /**\r\n * @dev Returns the account approved for `tokenId` token.\r\n *\r\n * Requirements:\r\n *\r\n * - `tokenId` must exist.\r\n */\r\n function getApproved(uint256 tokenId) external view returns (address operator);\r\n\r\n /**\r\n * @dev Approve or remove `operator` as an operator for the caller.\r\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\r\n *\r\n * Requirements:\r\n *\r\n * - The `operator` cannot be the caller.\r\n *\r\n * Emits an {ApprovalForAll} event.\r\n */\r\n function setApprovalForAll(address operator, bool _approved) external;\r\n\r\n /**\r\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\r\n *\r\n * See {setApprovalForAll}\r\n */\r\n function isApprovedForAll(address owner, address operator) external view returns (bool);\r\n\r\n /**\r\n * @dev Safely transfers `tokenId` token from `from` to `to`.\r\n *\r\n * Requirements:\r\n *\r\n * - `from` cannot be the zero address.\r\n * - `to` cannot be the zero address.\r\n * - `tokenId` token must exist and be owned by `from`.\r\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n *\r\n * Emits a {Transfer} event.\r\n */\r\n function safeTransferFrom(\r\n address from,\r\n address to,\r\n uint256 tokenId,\r\n bytes calldata data\r\n ) external;\r\n}\r\n"},"Ownable.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (access/Ownable.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\nimport \"./Context.sol\";\r\n\r\n/**\r\n * @dev Contract module which provides a basic access control mechanism, where\r\n * there is an account (an owner) that can be granted exclusive access to\r\n * specific functions.\r\n *\r\n * By default, the owner account will be the one that deploys the contract. This\r\n * can later be changed with {transferOwnership}.\r\n *\r\n * This module is used through inheritance. It will make available the modifier\r\n * `onlyOwner`, which can be applied to your functions to restrict their use to\r\n * the owner.\r\n */\r\nabstract contract Ownable is Context {\r\n address private _owner;\r\n\r\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\r\n\r\n /**\r\n * @dev Initializes the contract setting the deployer as the initial owner.\r\n */\r\n constructor() {\r\n _transferOwnership(_msgSender());\r\n }\r\n\r\n /**\r\n * @dev Returns the address of the current owner.\r\n */\r\n function owner() public view virtual returns (address) {\r\n return _owner;\r\n }\r\n\r\n /**\r\n * @dev Throws if called by any account other than the owner.\r\n */\r\n modifier onlyOwner() {\r\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\r\n _;\r\n }\r\n\r\n /**\r\n * @dev Leaves the contract without owner. It will not be possible to call\r\n * `onlyOwner` functions anymore. Can only be called by the current owner.\r\n *\r\n * NOTE: Renouncing ownership will leave the contract without an owner,\r\n * thereby removing any functionality that is only available to the owner.\r\n */\r\n function renounceOwnership() public virtual onlyOwner {\r\n _transferOwnership(address(0));\r\n }\r\n\r\n /**\r\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\r\n * Can only be called by the current owner.\r\n */\r\n function transferOwnership(address newOwner) public virtual onlyOwner {\r\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\r\n _transferOwnership(newOwner);\r\n }\r\n\r\n /**\r\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\r\n * Internal function without access restriction.\r\n */\r\n function _transferOwnership(address newOwner) internal virtual {\r\n address oldOwner = _owner;\r\n _owner = newOwner;\r\n emit OwnershipTransferred(oldOwner, newOwner);\r\n }\r\n}\r\n"},"Strings.sol":{"content":" SPDX-License-Identifier: MIT\r\n OpenZeppelin Contracts v4.3.2 (utils/Strings.sol)\r\n\r\npragma solidity ^0.8.0;\r\n\r\n/**\r\n * @dev String operations.\r\n */\r\nlibrary Strings {\r\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\r\n */\r\n function toString(uint256 value) internal pure returns (string memory) {\r\n Inspired by OraclizeAPI\u0027s implementation - MIT licence\r\n https:github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n if (value == 0) {\r\n return \"0\";\r\n }\r\n uint256 temp = value;\r\n uint256 digits;\r\n while (temp != 0) {\r\n digits++;\r\n temp /= 10;\r\n }\r\n bytes memory buffer = new bytes(digits);\r\n while (value != 0) {\r\n digits -= 1;\r\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n value /= 10;\r\n }\r\n return string(buffer);\r\n }\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\r\n */\r\n function toHexString(uint256 value) internal pure returns (string memory) {\r\n if (value == 0) {\r\n return \"0x00\";\r\n }\r\n uint256 temp = value;\r\n uint256 length = 0;\r\n while (temp != 0) {\r\n length++;\r\n temp \u003e\u003e= 8;\r\n }\r\n return toHexString(value, length);\r\n }\r\n\r\n /**\r\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\r\n */\r\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\r\n bytes memory buffer = new bytes(2 * length + 2);\r\n buffer[0] = \"0\";\r\n buffer[1] = \"x\";\r\n for (uint256 i = 2 * length + 1; i \u003e 1; --i) {\r\n buffer[i] = _HEX_SYMBOLS[value \u0026 0xf];\r\n value \u003e\u003e= 4;\r\n }\r\n require(value == 0, \"Strings: hex length insufficient\");\r\n return string(buffer);\r\n }\r\n}\r\n"}}
{"BlubStakingV3.sol":{"content":"
12,634,234
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 64, 86, 64, 82, 683, 9454, 18035, 560, 521, 89, 25425, 73, 33, 374, 18, 28, 18, 27, 9747, 86, 64, 82, 64, 86, 64, 82, 5666, 1239, 18, 19, 5460, 429, 18, 18281, 2412, 9747, 86, 64, 82, 5666, 1239, 18, 19, 7228, 19748, 18, 18281, 2412, 9747, 86, 64, 82, 5666, 1239, 18, 19, 7957, 18, 18281, 2412, 9747, 86, 64, 82, 5666, 1239, 18, 19, 45, 654, 39, 27, 5340, 18, 18281, 2412, 9747, 86, 64, 82, 64, 86, 64, 82, 5831, 467, 4802, 373, 1345, 18890, 86, 64, 82, 565, 445, 312, 474, 4446, 8924, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 9747, 86, 64, 82, 6280, 86, 64, 82, 64, 86, 64, 82, 16351, 8069, 373, 510, 6159, 353, 14223, 6914, 18890, 86, 64, 82, 565, 1450, 7773, 19748, 364, 1731, 1578, 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, 16711, 4802, 373, 510, 6159, 58, 23, 18, 18281, 6877, 16711, 1745, 15563, 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 ]
/* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ pragma solidity 0.4.24; /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be 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 { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Pausable.sol version: 1.0 author: Kevin Brown date: 2018-05-22 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be marked as paused. It also defines a modifier which can be used by the inheriting contract to prevent actions while paused. ----------------------------------------------------------------- */ /** * @title A contract that can be paused by its owner */ contract Pausable is Owned { uint public lastPauseTime; bool public paused; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we&#39;re actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 1.0 author: Anton Jurisevic date: 2018-2-5 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A fixed point decimal library that provides basic mathematical operations, and checks for unsafe arguments, for example that would lead to overflows. Exceptions are thrown whenever those unsafe operations occur. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals (including fiat, ether, and nomin quantities). */ contract SafeDecimalMath { /* Number of decimal places in the representation. */ uint8 public constant decimals = 18; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /** * @return True iff adding x and y will not overflow. */ function addIsSafe(uint x, uint y) pure internal returns (bool) { return x + y >= y; } /** * @return The result of adding x and y, throwing an exception in case of overflow. */ function safeAdd(uint x, uint y) pure internal returns (uint) { require(x + y >= y, "Safe add failed"); return x + y; } /** * @return True iff subtracting y from x will not overflow in the negative direction. */ function subIsSafe(uint x, uint y) pure internal returns (bool) { return y <= x; } /** * @return The result of subtracting y from x, throwing an exception in case of overflow. */ function safeSub(uint x, uint y) pure internal returns (uint) { require(y <= x, "Safe sub failed"); return x - y; } /** * @return True iff multiplying x and y would not overflow. */ function mulIsSafe(uint x, uint y) pure internal returns (bool) { if (x == 0) { return true; } return (x * y) / x == y; } /** * @return The result of multiplying x and y, throwing an exception in case of overflow. */ function safeMul(uint x, uint y) pure internal returns (uint) { if (x == 0) { return 0; } uint p = x * y; require(p / x == y, "Safe mul failed"); return p; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. Throws an exception in case of overflow. * * @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. * Incidentally, the internal division always rounds down: one could have rounded to the nearest integer, * but then one would be spending a significant fraction of a cent (of order a microether * at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands * contain small enough fractional components. It would also marginally diminish the * domain this function is defined upon. */ function safeMul_dec(uint x, uint y) pure internal returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return safeMul(x, y) / UNIT; } /** * @return True iff the denominator of x/y is nonzero. */ function divIsSafe(uint x, uint y) pure internal returns (bool) { return y != 0; } /** * @return The result of dividing x by y, throwing an exception if the divisor is zero. */ function safeDiv(uint x, uint y) pure internal returns (uint) { /* Although a 0 denominator already throws an exception, * it is equivalent to a THROW operation, which consumes all gas. * A require statement emits REVERT instead, which remits remaining gas. */ require(y != 0, "Denominator cannot be zero"); return x / y; } /** * @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers. * @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT. * Internal rounding is downward: a similar caveat holds as with safeDecMul(). */ function safeDiv_dec(uint x, uint y) pure internal returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return safeDiv(safeMul(x, UNIT), y); } /** * @dev Convert an unsigned integer to a unsigned fixed-point decimal. * Throw an exception if the result would be out of range. */ function intToDec(uint i) pure internal returns (uint) { return safeMul(i, UNIT); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: TokenState.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that holds the state of an ERC20 compliant token. This contract is used side by side with external state token contracts, such as Havven and Nomin. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */ /** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */ contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party&#39;s behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxy.sol version: 1.3 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxy contract that, if it does not recognise the function being called on it, passes all value and call data to an underlying target contract. This proxy has the capacity to toggle between DELEGATECALL and CALL style proxy functionality. The former executes in the proxy&#39;s context, and so will preserve msg.sender and store data at the proxy address. The latter will not. Therefore, any contract the proxy wraps in the CALL style must implement the Proxyable interface, in order that it can pass msg.sender into the underlying contract as the state parameter, messageSender. ----------------------------------------------------------------- */ contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { /* Copy call data into free memory region. */ let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* Forward all gas and call data to the target contract. */ let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) /* Revert if the call failed, otherwise return the result. */ if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { /* Here we are as above, but must send the messageSender explicitly * since we are using CALL rather than DELEGATECALL. */ target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target"); _; } event TargetUpdated(Proxyable newTarget); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Proxyable.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 checked: Mike Spain approved: Samuel Brooks ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A proxyable contract that works hand in hand with the Proxy contract to allow for anyone to interact with the underlying contract both directly and through the proxy. ----------------------------------------------------------------- */ // This contract should be treated like an abstract contract contract Proxyable is Owned { /* The proxy this contract exists behind. */ Proxy public proxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.0 author: Kevin Brown date: 2018-08-06 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract offers a modifer that can prevent reentrancy on particular actions. It will not work if you put it on multiple functions that can be called from each other. Specifically guard external entry points to the contract with the modifier only. ----------------------------------------------------------------- */ contract ReentrancyPreventer { /* ========== MODIFIERS ========== */ bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExternStateToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A partial ERC20 token contract, designed to operate with a proxy. To produce a complete ERC20 token, transfer and transferFrom tokens must be implemented, using the provided _byProxy internal functions. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */ contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, ReentrancyPreventer { /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. * Note that the decimals field is defined in SafeDecimalMath.*/ string public name; string public symbol; uint public totalSupply; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { name = _name; symbol = _symbol; totalSupply = _totalSupply; tokenState = _tokenState; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner&#39;s funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal preventReentrancy returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value)); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value)); /* If we&#39;re transferring to a contract and it implements the havvenTokenFallback function, call it. This isn&#39;t ERC223 compliant because: 1. We don&#39;t revert if the contract doesn&#39;t implement havvenTokenFallback. This is because many DEXes and other contracts that expect to work with the standard approve / transferFrom workflow don&#39;t implement tokenFallback but can still process our tokens as usual, so it feels very harsh and likely to cause trouble if we add this restriction after having previously gone live with a vanilla ERC20. 2. We don&#39;t pass the bytes parameter. This is because of this solidity bug: https://github.com/ethereum/solidity/issues/2884 3. We also don&#39;t let the user use a custom tokenFallback. We figure as we&#39;re already not standards compliant, there won&#39;t be a use case where users can&#39;t just implement our specific function. As such we&#39;ve called the function havvenTokenFallback to be clear that we are not following the standard. */ // Is the to address a contract? We can check the code size on that address and know. uint length; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on the recipient address length := extcodesize(to) } // If there&#39;s code there, it&#39;s a contract if (length > 0) { // Now we need to optionally call havvenTokenFallback(address from, uint value). // We can&#39;t call it the normal way because that reverts when the recipient doesn&#39;t implement the function. // We&#39;ll use .call(), which means we need the function selector. We&#39;ve pre-computed // abi.encodeWithSignature("havvenTokenFallback(address,uint256)"), to save some gas. // solium-disable-next-line security/no-low-level-calls to.call(0xcbff5d96, messageSender, value); // And yes, we specifically don&#39;t care if this call fails, so we&#39;re not checking the return value. } // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender&#39;s behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: FeeToken.sol version: 1.3 author: Anton Jurisevic Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A token which also has a configurable fee rate charged on its transfers. This is designed to be overridden in order to produce an ERC20-compliant token. These fees accrue into a pool, from which a nominated authority may withdraw. This contract utilises an external state for upgradeability. ----------------------------------------------------------------- */ /** * @title ERC20 Token contract, with detached state. * Additionally charges fees on each transfer. */ contract FeeToken is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* ERC20 members are declared in ExternStateToken. */ /* A percentage fee charged on each transfer. */ uint public transferFeeRate; /* Fee may not exceed 10%. */ uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10; /* The address with the authority to distribute fees. */ address public feeAuthority; /* The address that fees will be pooled in. */ address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token&#39;s ERC20 name. * @param _symbol Token&#39;s ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _transferFeeRate The fee rate to charge on transfers. * @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint _transferFeeRate, address _feeAuthority, address _owner) ExternStateToken(_proxy, _tokenState, _name, _symbol, _totalSupply, _owner) public { feeAuthority = _feeAuthority; /* Constructed transfer fee rate should respect the maximum fee rate. */ require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); transferFeeRate = _transferFeeRate; } /* ========== SETTERS ========== */ /** * @notice Set the transfer fee, anywhere within the range 0-10%. * @dev The fee rate is in decimal format, with UNIT being the value of 100%. */ function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeRateUpdated(_transferFeeRate); } /** * @notice Set the address of the user/contract responsible for collecting or * distributing fees. */ function setFeeAuthority(address _feeAuthority) public optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } /* ========== VIEWS ========== */ /** * @notice Calculate the Fee charged on top of a value being sent * @return Return the fee charged */ function transferFeeIncurred(uint value) public view returns (uint) { return safeMul_dec(value, transferFeeRate); /* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees. * This is on the basis that transfers less than this value will result in a nil fee. * Probably too insignificant to worry about, but the following code will achieve it. * if (fee == 0 && transferFeeRate != 0) { * return _value; * } * return fee; */ } /** * @notice The value that you would need to send so that the recipient receives * a specified value. */ function transferPlusFee(uint value) external view returns (uint) { return safeAdd(value, transferFeeIncurred(value)); } /** * @notice The amount the recipient will receive if you send a certain number of tokens. */ function amountReceived(uint value) public view returns (uint) { return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate)); } /** * @notice Collected fees sit here until they are distributed. * @dev The balance of the nomin contract itself is the fee pool. */ function feePool() external view returns (uint) { return tokenState.balanceOf(FEE_ADDRESS); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Base of transfer functions */ function _internalTransfer(address from, address to, uint amount, uint fee) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); /* Insufficient balance will be handled by the safe subtraction. */ tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee))); tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee)); /* Emit events for both the transfer itself and the fee. */ emitTransfer(from, to, amount); emitTransfer(from, FEE_ADDRESS, fee); return true; } /** * @notice ERC20 friendly transfer function. */ function _transfer_byProxy(address sender, address to, uint value) internal returns (bool) { uint received = amountReceived(value); uint fee = safeSub(value, received); return _internalTransfer(sender, to, received, fee); } /** * @notice ERC20 friendly transferFrom function. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is deducted from the amount sent. */ uint received = amountReceived(value); uint fee = safeSub(value, received); /* Reduce the allowance by the amount we&#39;re transferring. * The safeSub call will handle an insufficient allowance. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value)); return _internalTransfer(from, to, received, fee); } /** * @notice Ability to transfer where the sender pays the fees (not ERC20) */ function _transferSenderPaysFee_byProxy(address sender, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); return _internalTransfer(sender, to, value, fee); } /** * @notice Ability to transferFrom where they sender pays the fees (not ERC20). */ function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* The fee is added to the amount sent. */ uint fee = transferFeeIncurred(value); uint total = safeAdd(value, fee); /* Reduce the allowance by the amount we&#39;re transferring. */ tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total)); return _internalTransfer(from, to, value, fee); } /** * @notice Withdraw tokens from the fee pool into a given account. * @dev Only the fee authority may call this. */ function withdrawFees(address account, uint value) external onlyFeeAuthority returns (bool) { require(account != address(0), "Must supply an account address to withdraw fees"); /* 0-value withdrawals do nothing. */ if (value == 0) { return false; } /* Safe subtraction ensures an exception is thrown if the balance is insufficient. */ tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value)); tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value)); emitFeesWithdrawn(account, value); emitTransfer(FEE_ADDRESS, account, value); return true; } /** * @notice Donate tokens from the sender&#39;s balance into the fee pool. */ function donateToFeePool(uint n) external optionalProxy returns (bool) { address sender = messageSender; /* Empty donations are disallowed. */ uint balance = tokenState.balanceOf(sender); require(balance != 0, "Must have a balance in order to donate to the fee pool"); /* safeSub ensures the donor has sufficient balance. */ tokenState.setBalanceOf(sender, safeSub(balance, n)); tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n)); emitFeesDonated(sender, n); emitTransfer(sender, FEE_ADDRESS, n); return true; } /* ========== MODIFIERS ========== */ modifier onlyFeeAuthority { require(msg.sender == feeAuthority, "Only the fee authority can do this action"); _; } /* ========== EVENTS ========== */ event TransferFeeRateUpdated(uint newFeeRate); bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)"); function emitTransferFeeRateUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event FeesDonated(address indexed donor, uint value); bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)"); function emitFeesDonated(address donor, uint value) internal { proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Nomin.sol version: 1.2 author: Anton Jurisevic Mike Spain Dominic Romanowski Kevin Brown date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven-backed nomin stablecoin contract. This contract issues nomins, which are tokens worth 1 USD each. Nomins are issuable by Havven holders who have to lock up some value of their havvens to issue H * Cmax nomins. Where Cmax is some value less than 1. A configurable fee is charged on nomin transfers and deposited into a common pot, which havven holders may withdraw from once per fee period. ----------------------------------------------------------------- */ contract Nomin is FeeToken { /* ========== STATE VARIABLES ========== */ Havven public havven; // Accounts which have lost the privilege to transact in nomins. mapping(address => bool) public frozen; // Nomin transfers incur a 15 bp fee by default. uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000; string constant TOKEN_NAME = "Nomin USD"; string constant TOKEN_SYMBOL = "nUSD"; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, Havven _havven, uint _totalSupply, address _owner) FeeToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, TRANSFER_FEE_RATE, _havven, // The havven contract is the fee authority. _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_havven) != 0, "_havven cannot be 0"); require(_owner != 0, "_owner cannot be 0"); // It should not be possible to transfer to the fee pool directly (or confiscate its balance). frozen[FEE_ADDRESS] = true; havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external optionalProxy_onlyOwner { // havven should be set as the feeAuthority after calling this depending on // havven&#39;s internal logic havven = _havven; setFeeAuthority(_havven); emitHavvenUpdated(_havven); } /* ========== MUTATIVE FUNCTIONS ========== */ /* Override ERC20 transfer function in order to check * whether the recipient account is frozen. Note that there is * no need to check whether the sender has a frozen account, * since their funds have already been confiscated, * and no new funds can be transferred to it.*/ function transfer(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transfer_byProxy(messageSender, to, value); } /* Override ERC20 transferFrom function in order to check * whether the recipient account is frozen. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFrom_byProxy(messageSender, from, to, value); } function transferSenderPaysFee(address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferSenderPaysFee_byProxy(messageSender, to, value); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy returns (bool) { require(!frozen[to], "Cannot transfer to frozen address"); return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value); } /* The owner may allow a previously-frozen contract to once * again accept and transfer nomins. */ function unfreezeAccount(address target) external optionalProxy_onlyOwner { require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address"); frozen[target] = false; emitAccountUnfrozen(target); } /* Allow havven to issue a certain number of * nomins from an account. */ function issue(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount)); totalSupply = safeAdd(totalSupply, amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } /* Allow havven to burn a certain number of * nomins from an account. */ function burn(address account, uint amount) external onlyHavven { tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } /* ========== MODIFIERS ========== */ modifier onlyHavven() { require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action"); _; } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)"); function emitHavvenUpdated(address newHavven) internal { proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0); } event AccountFrozen(address indexed target, uint balance); bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)"); function emitAccountFrozen(address target, uint balance) internal { proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0); } event AccountUnfrozen(address indexed target); bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)"); function emitAccountUnfrozen(address target) internal { proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0); } event Issued(address indexed account, uint amount); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint amount); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint amount) internal { proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: LimitedSetup.sol version: 1.1 author: Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract with a limited setup period. Any function modified with the setup modifier will cease to work after the conclusion of the configurable-length post-construction setup period. ----------------------------------------------------------------- */ /** * @title Any function decorated with the modifier this contract provides * deactivates after a specified setup period. */ contract LimitedSetup { uint setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: HavvenEscrow.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski Mike Spain date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows the foundation to apply unique vesting schedules to havven funds sold at various discounts in the token sale. HavvenEscrow gives users the ability to inspect their vested funds, their quantities and vesting dates, and to withdraw the fees that accrue on those funds. The fees are handled by withdrawing the entire fee allocation for all havvens inside the escrow contract, and then allowing the contract itself to subdivide that pool up proportionally within itself. Every time the fee period rolls over in the main Havven contract, the HavvenEscrow fee pool is remitted back into the main fee pool to be redistributed in the next fee period. ----------------------------------------------------------------- */ /** * @title A contract to hold escrowed havvens and free them at given schedules. */ contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) { /* The corresponding Havven contract. */ Havven public havven; /* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order. * These are the times at which each given quantity of havvens vests. */ mapping(address => uint[2][]) public vestingSchedules; /* An account&#39;s total vested havven balance to save recomputing this for fee extraction purposes. */ mapping(address => uint) public totalVestedAccountBalance; /* The total remaining vested balance, for verifying the actual havven balance of this contract against. */ uint public totalVestedBalance; uint constant TIME_INDEX = 0; uint constant QUANTITY_INDEX = 1; /* Limit vesting entries to disallow unbounded iteration over vesting schedules. */ uint constant MAX_VESTING_ENTRIES = 20; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, Havven _havven) Owned(_owner) public { havven = _havven; } /* ========== SETTERS ========== */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /* ========== VIEW FUNCTIONS ========== */ /** * @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration. */ function balanceOf(address account) public view returns (uint) { return totalVestedAccountBalance[account]; } /** * @notice The number of vesting dates in an account&#39;s schedule. */ function numVestingEntries(address account) public view returns (uint) { return vestingSchedules[account].length; } /** * @notice Get a particular schedule entry for an account. * @return A pair of uints: (timestamp, havven quantity). */ function getVestingScheduleEntry(address account, uint index) public view returns (uint[2]) { return vestingSchedules[account][index]; } /** * @notice Get the time at which a given schedule entry will vest. */ function getVestingTime(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[TIME_INDEX]; } /** * @notice Get the quantity of havvens associated with a given schedule entry. */ function getVestingQuantity(address account, uint index) public view returns (uint) { return getVestingScheduleEntry(account,index)[QUANTITY_INDEX]; } /** * @notice Obtain the index of the next schedule entry that will vest for a given user. */ function getNextVestingIndex(address account) public view returns (uint) { uint len = numVestingEntries(account); for (uint i = 0; i < len; i++) { if (getVestingTime(account, i) != 0) { return i; } } return len; } /** * @notice Obtain the next schedule entry that will vest for a given user. * @return A pair of uints: (timestamp, havven quantity). */ function getNextVestingEntry(address account) public view returns (uint[2]) { uint index = getNextVestingIndex(account); if (index == numVestingEntries(account)) { return [uint(0), 0]; } return getVestingScheduleEntry(account, index); } /** * @notice Obtain the time at which the next schedule entry will vest for a given user. */ function getNextVestingTime(address account) external view returns (uint) { return getNextVestingEntry(account)[TIME_INDEX]; } /** * @notice Obtain the quantity which the next schedule entry will vest for a given user. */ function getNextVestingQuantity(address account) external view returns (uint) { return getNextVestingEntry(account)[QUANTITY_INDEX]; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Withdraws a quantity of havvens back to the havven contract. * @dev This may only be called by the owner during the contract&#39;s setup period. */ function withdrawHavvens(uint quantity) external onlyOwner onlyDuringSetup { havven.transfer(havven, quantity); } /** * @notice Destroy the vesting information associated with an account. */ function purgeAccount(address account) external onlyOwner onlyDuringSetup { delete vestingSchedules[account]; totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]); delete totalVestedAccountBalance[account]; } /** * @notice Add a new vesting entry at a given time and quantity to an account&#39;s schedule. * @dev A call to this should be accompanied by either enough balance already available * in this contract, or a corresponding call to havven.endow(), to ensure that when * the funds are withdrawn, there is enough balance, as well as correctly calculating * the fees. * This may only be called by the owner during the contract&#39;s setup period. * Note; although this function could technically be used to produce unbounded * arrays, it&#39;s only in the foundation&#39;s command to add to these lists. * @param account The account to append a new vesting entry to. * @param time The absolute unix timestamp after which the vested quantity may be withdrawn. * @param quantity The quantity of havvens that will vest. */ function appendVestingEntry(address account, uint time, uint quantity) public onlyOwner onlyDuringSetup { /* No empty or already-passed vesting entries allowed. */ require(now < time, "Time must be in the future"); require(quantity != 0, "Quantity cannot be zero"); /* There must be enough balance in the contract to provide for the vesting entry. */ totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry"); /* Disallow arbitrarily long vesting schedules in light of the gas limit. */ uint scheduleLength = vestingSchedules[account].length; require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long"); if (scheduleLength == 0) { totalVestedAccountBalance[account] = quantity; } else { /* Disallow adding new vested havvens earlier than the last one. * Since entries are only appended, this means that no vesting date can be repeated. */ require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one"); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); } /** * @notice Construct a vesting schedule to release a quantities of havvens * over a series of intervals. * @dev Assumes that the quantities are nonzero * and that the sequence of timestamps is strictly increasing. * This may only be called by the owner during the contract&#39;s setup period. */ function addVestingSchedule(address account, uint[] times, uint[] quantities) external onlyOwner onlyDuringSetup { for (uint i = 0; i < times.length; i++) { appendVestingEntry(account, times[i], quantities[i]); } } /** * @notice Allow a user to withdraw any havvens in their schedule that have vested. */ function vest() external { uint numEntries = numVestingEntries(msg.sender); uint total; for (uint i = 0; i < numEntries; i++) { uint time = getVestingTime(msg.sender, i); /* The list is sorted; when we reach the first future time, bail out. */ if (time > now) { break; } uint qty = getVestingQuantity(msg.sender, i); if (qty == 0) { continue; } vestingSchedules[msg.sender][i] = [0, 0]; total = safeAdd(total, qty); } if (total != 0) { totalVestedBalance = safeSub(totalVestedBalance, total); totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total); havven.transfer(msg.sender, total); emit Vested(msg.sender, now, total); } } /* ========== EVENTS ========== */ event HavvenUpdated(address newHavven); event Vested(address indexed beneficiary, uint time, uint value); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Havven.sol version: 1.2 author: Anton Jurisevic Dominic Romanowski date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Havven token contract. Havvens are transferable ERC20 tokens, and also give their holders the following privileges. An owner of havvens may participate in nomin confiscation votes, they may also have the right to issue nomins at the discretion of the foundation for this version of the contract. After a fee period terminates, the duration and fees collected for that period are computed, and the next period begins. Thus an account may only withdraw the fees owed to them for the previous period, and may only do so once per period. Any unclaimed fees roll over into the common pot for the next period. == Average Balance Calculations == The fee entitlement of a havven holder is proportional to their average issued nomin balance over the last fee period. This is computed by measuring the area under the graph of a user&#39;s issued nomin balance over time, and then when a new fee period begins, dividing through by the duration of the fee period. We need only update values when the balances of an account is modified. This occurs when issuing or burning for issued nomin balances, and when transferring for havven balances. This is for efficiency, and adds an implicit friction to interacting with havvens. A havven holder pays for his own recomputation whenever he wants to change his position, which saves the foundation having to maintain a pot dedicated to resourcing this. A hypothetical user&#39;s balance history over one fee period, pictorially: s ____ | | | |___ p |____|___|___ __ _ _ f t n Here, the balance was s between times f and t, at which time a transfer occurred, updating the balance to p, until n, when the present transfer occurs. When a new transfer occurs at time n, the balance being p, we must: - Add the area p * (n - t) to the total area recorded so far - Update the last transfer time to n So if this graph represents the entire current fee period, the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f). The complementary computations must be performed for both sender and recipient. Note that a transfer keeps global supply of havvens invariant. The sum of all balances is constant, and unmodified by any transfer. So the sum of all balances multiplied by the duration of a fee period is also constant, and this is equivalent to the sum of the area of every user&#39;s time/balance graph. Dividing through by that duration yields back the total havven supply. So, at the end of a fee period, we really do yield a user&#39;s average share in the havven supply over that period. A slight wrinkle is introduced if we consider the time r when the fee period rolls over. Then the previous fee period k-1 is before r, and the current fee period k is afterwards. If the last transfer took place before r, but the latest transfer occurred afterwards: k-1 | k s __|_ | | | | | |____ p |__|_|____|___ __ _ _ | f | t n r In this situation the area (r-f)*s contributes to fee period k-1, while the area (t-r)*s contributes to fee period k. We will implicitly consider a zero-value transfer to have occurred at time r. Their fee entitlement for the previous period will be finalised at the time of their first transfer during the current fee period, or when they query or withdraw their fee entitlement. In the implementation, the duration of different fee periods may be slightly irregular, as the check that they have rolled over occurs only when state-changing havven operations are performed. == Issuance and Burning == In this version of the havven contract, nomins can only be issued by those that have been nominated by the havven foundation. Nomins are assumed to be valued at $1, as they are a stable unit of account. All nomins issued require a proportional value of havvens to be locked, where the proportion is governed by the current issuance ratio. This means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued. i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up. To determine the value of some amount of havvens(H), an oracle is used to push the price of havvens (P_H) in dollars to the contract. The value of H would then be: H * P_H. Any havvens that are locked up by this issuance process cannot be transferred. The amount that is locked floats based on the price of havvens. If the price of havvens moves up, less havvens are locked, so they can be issued against, or transferred freely. If the price of havvens moves down, more havvens are locked, even going above the initial wallet balance. ----------------------------------------------------------------- */ /** * @title Havven ERC20 contract. * @notice The Havven contracts does not only facilitate transfers and track balances, * but it also computes the quantity of fees each havven holder is entitled to. */ contract Havven is ExternStateToken { /* ========== STATE VARIABLES ========== */ /* A struct for handing values associated with average balance calculations */ struct IssuanceData { /* Sums of balances*duration in the current fee period. /* range: decimals; units: havven-seconds */ uint currentBalanceSum; /* The last period&#39;s average balance */ uint lastAverageBalance; /* The last time the data was calculated */ uint lastModified; } /* Issued nomin balances for individual fee entitlements */ mapping(address => IssuanceData) public issuanceData; /* The total number of issued nomins for determining fee entitlements */ IssuanceData public totalIssuanceData; /* The time the current fee period began */ uint public feePeriodStartTime; /* The time the last fee period began */ uint public lastFeePeriodStartTime; /* Fee periods will roll over in no shorter a time than this. * The fee period cannot actually roll over until a fee-relevant * operation such as withdrawal or a fee period duration update occurs, * so this is just a target, and the actual duration may be slightly longer. */ uint public feePeriodDuration = 4 weeks; /* ...and must target between 1 day and six months. */ uint constant MIN_FEE_PERIOD_DURATION = 1 days; uint constant MAX_FEE_PERIOD_DURATION = 26 weeks; /* The quantity of nomins that were in the fee pot at the time */ /* of the last fee rollover, at feePeriodStartTime. */ uint public lastFeesCollected; /* Whether a user has withdrawn their last fees */ mapping(address => bool) public hasWithdrawnFees; Nomin public nomin; HavvenEscrow public escrow; /* The address of the oracle which pushes the havven price to this contract */ address public oracle; /* The price of havvens written in UNIT */ uint public price; /* The time the havven price was last updated */ uint public lastPriceUpdateTime; /* How long will the contract assume the price of havvens is correct */ uint public priceStalePeriod = 3 hours; /* A quantity of nomins greater than this ratio * may not be issued against a given value of havvens. */ uint public issuanceRatio = UNIT / 5; /* No more nomins may be issued than the value of havvens backing them. */ uint constant MAX_ISSUANCE_RATIO = UNIT; /* Whether the address can issue nomins or not. */ mapping(address => bool) public isIssuer; /* The number of currently-outstanding nomins the user has issued. */ mapping(address => uint) public nominsIssued; uint constant HAVVEN_SUPPLY = 1e8 * UNIT; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; string constant TOKEN_NAME = "Havven"; string constant TOKEN_SYMBOL = "HAV"; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _tokenState A pre-populated contract containing token balances. * If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle, uint _price, address[] _issuers, Havven _oldHavven) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner) public { oracle = _oracle; price = _price; lastPriceUpdateTime = now; uint i; if (_oldHavven == address(0)) { feePeriodStartTime = now; lastFeePeriodStartTime = now - feePeriodDuration; for (i = 0; i < _issuers.length; i++) { isIssuer[_issuers[i]] = true; } } else { feePeriodStartTime = _oldHavven.feePeriodStartTime(); lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime(); uint cbs; uint lab; uint lm; (cbs, lab, lm) = _oldHavven.totalIssuanceData(); totalIssuanceData.currentBalanceSum = cbs; totalIssuanceData.lastAverageBalance = lab; totalIssuanceData.lastModified = lm; for (i = 0; i < _issuers.length; i++) { address issuer = _issuers[i]; isIssuer[issuer] = true; uint nomins = _oldHavven.nominsIssued(issuer); if (nomins == 0) { // It is not valid in general to skip those with no currently-issued nomins. // But for this release, issuers with nonzero issuanceData have current issuance. continue; } (cbs, lab, lm) = _oldHavven.issuanceData(issuer); nominsIssued[issuer] = nomins; issuanceData[issuer].currentBalanceSum = cbs; issuanceData[issuer].lastAverageBalance = lab; issuanceData[issuer].lastModified = lm; } } } /* ========== SETTERS ========== */ /** * @notice Set the associated Nomin contract to collect fees from. * @dev Only the contract owner may call this. */ function setNomin(Nomin _nomin) external optionalProxy_onlyOwner { nomin = _nomin; emitNominUpdated(_nomin); } /** * @notice Set the associated havven escrow contract. * @dev Only the contract owner may call this. */ function setEscrow(HavvenEscrow _escrow) external optionalProxy_onlyOwner { escrow = _escrow; emitEscrowUpdated(_escrow); } /** * @notice Set the targeted fee period duration. * @dev Only callable by the contract owner. The duration must fall within * acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period * may roll over if the target duration was shortened sufficiently. */ function setFeePeriodDuration(uint duration) external optionalProxy_onlyOwner { require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION, "Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION"); feePeriodDuration = duration; emitFeePeriodDurationUpdated(duration); rolloverFeePeriodIfElapsed(); } /** * @notice Set the Oracle that pushes the havven price to this contract */ function setOracle(address _oracle) external optionalProxy_onlyOwner { oracle = _oracle; emitOracleUpdated(_oracle); } /** * @notice Set the stale period on the updated havven price * @dev No max/minimum, as changing it wont influence anything but issuance by the foundation */ function setPriceStalePeriod(uint time) external optionalProxy_onlyOwner { priceStalePeriod = time; } /** * @notice Set the issuanceRatio for issuance calculations. * @dev Only callable by the contract owner. */ function setIssuanceRatio(uint _issuanceRatio) external optionalProxy_onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emitIssuanceRatioUpdated(_issuanceRatio); } /** * @notice Set whether the specified can issue nomins or not. */ function setIssuer(address account, bool value) external optionalProxy_onlyOwner { isIssuer[account] = value; emitIssuersUpdated(account, value); } /* ========== VIEWS ========== */ function issuanceCurrentBalanceSum(address account) external view returns (uint) { return issuanceData[account].currentBalanceSum; } function issuanceLastAverageBalance(address account) external view returns (uint) { return issuanceData[account].lastAverageBalance; } function issuanceLastModified(address account) external view returns (uint) { return issuanceData[account].lastModified; } function totalIssuanceCurrentBalanceSum() external view returns (uint) { return totalIssuanceData.currentBalanceSum; } function totalIssuanceLastAverageBalance() external view returns (uint) { return totalIssuanceData.lastAverageBalance; } function totalIssuanceLastModified() external view returns (uint) { return totalIssuanceData.lastModified; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function. */ function transfer(address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transfer_byProxy(sender, to, value); return true; } /** * @notice ERC20 transferFrom function. */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { address sender = messageSender; require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens"); /* Perform the transfer: if there is a problem, * an exception will be thrown in this call. */ _transferFrom_byProxy(sender, from, to, value); return true; } /** * @notice Compute the last period&#39;s fee entitlement for the message sender * and then deposit it into their nomin account. */ function withdrawFees() external optionalProxy { address sender = messageSender; rolloverFeePeriodIfElapsed(); /* Do not deposit fees into frozen accounts. */ require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts"); /* Check the period has rolled over first. */ updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply()); /* Only allow accounts to withdraw fees once per period. */ require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period"); uint feesOwed; uint lastTotalIssued = totalIssuanceData.lastAverageBalance; if (lastTotalIssued > 0) { /* Sender receives a share of last period&#39;s collected fees proportional * with their average fraction of the last period&#39;s issued nomins. */ feesOwed = safeDiv_dec( safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected), lastTotalIssued ); } hasWithdrawnFees[sender] = true; if (feesOwed != 0) { nomin.withdrawFees(sender, feesOwed); } emitFeesWithdrawn(messageSender, feesOwed); } /** * @notice Update the havven balance averages since the last transfer * or entitlement adjustment. * @dev Since this updates the last transfer timestamp, if invoked * consecutively, this function will do nothing after the first call. * Also, this will adjust the total issuance at the same time. */ function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply) internal { /* update the total balances first */ totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData); if (issuanceData[account].lastModified < feePeriodStartTime) { hasWithdrawnFees[account] = false; } issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]); } /** * @notice Compute the new IssuanceData on the old balance */ function computeIssuanceData(uint preBalance, IssuanceData preIssuance) internal view returns (IssuanceData) { uint currentBalanceSum = preIssuance.currentBalanceSum; uint lastAverageBalance = preIssuance.lastAverageBalance; uint lastModified = preIssuance.lastModified; if (lastModified < feePeriodStartTime) { if (lastModified < lastFeePeriodStartTime) { /* The balance was last updated before the previous fee period, so the average * balance in this period is their pre-transfer balance. */ lastAverageBalance = preBalance; } else { /* The balance was last updated during the previous fee period. */ /* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified. * implies these quantities are strictly positive. */ uint timeUpToRollover = feePeriodStartTime - lastModified; uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime; uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover)); lastAverageBalance = lastBalanceSum / lastFeePeriodDuration; } /* Roll over to the next fee period. */ currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime); } else { /* The balance was last updated during the current fee period. */ currentBalanceSum = safeAdd( currentBalanceSum, safeMul(preBalance, now - lastModified) ); } return IssuanceData(currentBalanceSum, lastAverageBalance, now); } /** * @notice Recompute and return the given account&#39;s last average balance. */ function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; } /** * @notice Issue nomins against the sender&#39;s havvens. * @dev Issuance is only allowed if the havven price isn&#39;t stale and the sender is an issuer. */ function issueNomins(uint amount) public optionalProxy requireIssuer(messageSender) /* No need to check if price is stale, as it is checked in issuableNomins. */ { address sender = messageSender; require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins"); uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; nomin.issue(sender, amount); nominsIssued[sender] = safeAdd(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } function issueMaxNomins() external optionalProxy { issueNomins(remainingIssuableNomins(messageSender)); } /** * @notice Burn nomins to clear issued nomins/free havvens. */ function burnNomins(uint amount) /* it doesn&#39;t matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/ external optionalProxy { address sender = messageSender; uint lastTot = nomin.totalSupply(); uint preIssued = nominsIssued[sender]; /* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */ nomin.burn(sender, amount); /* This safe sub ensures amount <= number issued */ nominsIssued[sender] = safeSub(preIssued, amount); updateIssuanceData(sender, preIssued, lastTot); } /** * @notice Check if the fee period has rolled over. If it has, set the new fee period start * time, and record the fees collected in the nomin contract. */ function rolloverFeePeriodIfElapsed() public { /* If the fee period has rolled over... */ if (now >= feePeriodStartTime + feePeriodDuration) { lastFeesCollected = nomin.feePool(); lastFeePeriodStartTime = feePeriodStartTime; feePeriodStartTime = now; emitFeePeriodRollover(now); } } /* ========== Issuance/Burning ========== */ /** * @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any * already issued nomins. */ function maxIssuableNomins(address issuer) view public priceNotStale returns (uint) { if (!isIssuer[issuer]) { return 0; } if (escrow != HavvenEscrow(0)) { uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer)); return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio); } else { return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio); } } /** * @notice The remaining nomins an issuer can issue against their total havven quantity. */ function remainingIssuableNomins(address issuer) view public returns (uint) { uint issued = nominsIssued[issuer]; uint max = maxIssuableNomins(issuer); if (issued > max) { return 0; } else { return safeSub(max, issued); } } /** * @notice The total havvens owned by this account, both escrowed and unescrowed, * against which nomins can be issued. * This includes those already being used as collateral (locked), and those * available for further issuance (unlocked). */ function collateral(address account) public view returns (uint) { uint bal = tokenState.balanceOf(account); if (escrow != address(0)) { bal = safeAdd(bal, escrow.balanceOf(account)); } return bal; } /** * @notice The collateral that would be locked by issuance, which can exceed the account&#39;s actual collateral. */ function issuanceDraft(address account) public view returns (uint) { uint issued = nominsIssued[account]; if (issued == 0) { return 0; } return USDtoHAV(safeDiv_dec(issued, issuanceRatio)); } /** * @notice Collateral that has been locked due to issuance, and cannot be * transferred to other addresses. This is capped at the account&#39;s total collateral. */ function lockedCollateral(address account) public view returns (uint) { uint debt = issuanceDraft(account); uint collat = collateral(account); if (debt > collat) { return collat; } return debt; } /** * @notice Collateral that is not locked and available for issuance. */ function unlockedCollateral(address account) public view returns (uint) { uint locked = lockedCollateral(account); uint collat = collateral(account); return safeSub(collat, locked); } /** * @notice The number of havvens that are free to be transferred by an account. * @dev If they have enough available Havvens, it could be that * their havvens are escrowed, however the transfer would then * fail. This means that escrowed havvens are locked first, * and then the actual transferable ones. */ function transferableHavvens(address account) public view returns (uint) { uint draft = issuanceDraft(account); uint collat = collateral(account); // In the case where the issuanceDraft exceeds the collateral, nothing is free if (draft > collat) { return 0; } uint bal = balanceOf(account); // In the case where the draft exceeds the escrow, but not the whole collateral // return the fraction of the balance that remains free if (draft > safeSub(collat, bal)) { return safeSub(collat, draft); } // In the case where the draft doesn&#39;t exceed the escrow, return the entire balance return bal; } /** * @notice The value in USD for a given amount of HAV */ function HAVtoUSD(uint hav_dec) public view priceNotStale returns (uint) { return safeMul_dec(hav_dec, price); } /** * @notice The value in HAV for a given amount of USD */ function USDtoHAV(uint usd_dec) public view priceNotStale returns (uint) { return safeDiv_dec(usd_dec, price); } /** * @notice Access point for the oracle to update the price of havvens. */ function updatePrice(uint newPrice, uint timeSent) external onlyOracle /* Should be callable only by the oracle. */ { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); price = newPrice; lastPriceUpdateTime = timeSent; emitPriceUpdated(newPrice, timeSent); /* Check the fee period rollover within this as the price should be pushed every 15min. */ rolloverFeePeriodIfElapsed(); } /** * @notice Check if the price of havvens hasn&#39;t been updated for longer than the stale period. */ function priceIsStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /* ========== MODIFIERS ========== */ modifier requireIssuer(address account) { require(isIssuer[account], "Must be issuer to perform this action"); _; } modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier priceNotStale { require(!priceIsStale(), "Price must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event PriceUpdated(uint newPrice, uint timestamp); bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)"); function emitPriceUpdated(uint newPrice, uint timestamp) internal { proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0); } event IssuanceRatioUpdated(uint newRatio); bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)"); function emitIssuanceRatioUpdated(uint newRatio) internal { proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0); } event FeePeriodRollover(uint timestamp); bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)"); function emitFeePeriodRollover(uint timestamp) internal { proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint duration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint duration) internal { proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeesWithdrawn(address indexed account, uint value); bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)"); function emitFeesWithdrawn(address account, uint value) internal { proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0); } event OracleUpdated(address newOracle); bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)"); function emitOracleUpdated(address newOracle) internal { proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0); } event NominUpdated(address newNomin); bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)"); function emitNominUpdated(address newNomin) internal { proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0); } event EscrowUpdated(address newEscrow); bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)"); function emitEscrowUpdated(address newEscrow) internal { proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0); } event IssuersUpdated(address indexed account, bool indexed value); bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)"); function emitIssuersUpdated(address account, bool value) internal { proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0); } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: IssuanceController.sol version: 2.0 author: Kevin Brown date: 2018-07-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Issuance controller contract. The issuance controller provides a way for users to acquire nomins (Nomin.sol) and havvens (Havven.sol) by paying ETH and a way for users to acquire havvens (Havven.sol) by paying nomins. Users can also deposit their nomins and allow other users to purchase them with ETH. The ETH is sent to the user who offered their nomins for sale. This smart contract contains a balance of each currency, and allows the owner of the contract (the Havven Foundation) to manage the available balance of havven at their discretion, while users are allowed to deposit and withdraw their own nomin deposits if they have not yet been taken up by another user. ----------------------------------------------------------------- */ /** * @title Issuance Controller Contract. */ contract IssuanceController is SafeDecimalMath, SelfDestructible, Pausable { /* ========== STATE VARIABLES ========== */ Havven public havven; Nomin public nomin; // Address where the ether raised is transfered to address public fundsWallet; /* The address of the oracle which pushes the USD price havvens and ether to this contract */ address public oracle; /* Do not allow the oracle to submit times any further forward into the future than this constant. */ uint constant ORACLE_FUTURE_LIMIT = 10 minutes; /* How long will the contract assume the price of any asset is correct */ uint public priceStalePeriod = 3 hours; /* The time the prices were last updated */ uint public lastPriceUpdateTime; /* The USD price of havvens denominated in UNIT */ uint public usdToHavPrice; /* The USD price of ETH denominated in UNIT */ uint public usdToEthPrice; /* ========== CONSTRUCTOR ========== */ /** * @dev Constructor * @param _owner The owner of this contract. * @param _fundsWallet The recipient of ETH and Nomins that are sent to this contract while exchanging. * @param _havven The Havven contract we&#39;ll interact with for balances and sending. * @param _nomin The Nomin contract we&#39;ll interact with for balances and sending. * @param _oracle The address which is able to update price information. * @param _usdToEthPrice The current price of ETH in USD, expressed in UNIT. * @param _usdToHavPrice The current price of Havven in USD, expressed in UNIT. */ constructor( // Ownable address _owner, // Funds Wallet address _fundsWallet, // Other contracts needed Havven _havven, Nomin _nomin, // Oracle values - Allows for price updates address _oracle, uint _usdToEthPrice, uint _usdToHavPrice ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) Pausable(_owner) public { fundsWallet = _fundsWallet; havven = _havven; nomin = _nomin; oracle = _oracle; usdToEthPrice = _usdToEthPrice; usdToHavPrice = _usdToHavPrice; lastPriceUpdateTime = now; } /* ========== SETTERS ========== */ /** * @notice Set the funds wallet where ETH raised is held * @param _fundsWallet The new address to forward ETH and Nomins to */ function setFundsWallet(address _fundsWallet) external onlyOwner { fundsWallet = _fundsWallet; emit FundsWalletUpdated(fundsWallet); } /** * @notice Set the Oracle that pushes the havven price to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the Nomin contract that the issuance controller uses to issue Nomins. * @param _nomin The new nomin contract target */ function setNomin(Nomin _nomin) external onlyOwner { nomin = _nomin; emit NominUpdated(_nomin); } /** * @notice Set the Havven contract that the issuance controller uses to issue Havvens. * @param _havven The new havven contract target */ function setHavven(Havven _havven) external onlyOwner { havven = _havven; emit HavvenUpdated(_havven); } /** * @notice Set the stale period on the updated price variables * @param _time The new priceStalePeriod */ function setPriceStalePeriod(uint _time) external onlyOwner { priceStalePeriod = _time; emit PriceStalePeriodUpdated(priceStalePeriod); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Access point for the oracle to update the prices of havvens / eth. * @param newEthPrice The current price of ether in USD, specified to 18 decimal places. * @param newHavvenPrice The current price of havvens in USD, specified to 18 decimal places. * @param timeSent The timestamp from the oracle when the transaction was created. This ensures we don&#39;t consider stale prices as current in times of heavy network congestion. */ function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent) external onlyOracle { /* Must be the most recently sent price, but not too far in the future. * (so we can&#39;t lock ourselves out of updating the oracle for longer than this) */ require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT, "Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT"); usdToEthPrice = newEthPrice; usdToHavPrice = newHavvenPrice; lastPriceUpdateTime = timeSent; emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime); } /** * @notice Fallback function (exchanges ETH to nUSD) */ function () external payable { exchangeEtherForNomins(); } /** * @notice Exchange ETH to nUSD. */ function exchangeEtherForNomins() public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { // The multiplication works here because usdToEthPrice is specified in // 18 decimal places, just like our currency base. uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // Send the nomins. // Note: Fees are calculated by the Nomin contract, so when // we request a specific transfer here, the fee is // automatically deducted and sent to the fee pool. nomin.transfer(msg.sender, requestedToPurchase); emit Exchange("ETH", msg.value, "nUSD", requestedToPurchase); return requestedToPurchase; } /** * @notice Exchange ETH to nUSD while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param guaranteedRate The exchange rate (ether price) which must be honored or the call will revert. */ function exchangeEtherForNominsAtRate(uint guaranteedRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Nomins (nUSD) received { require(guaranteedRate == usdToEthPrice); return exchangeEtherForNomins(); } /** * @notice Exchange ETH to HAV. */ function exchangeEtherForHavvens() public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForEther(msg.value); // Store the ETH in our funds wallet fundsWallet.transfer(msg.value); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("ETH", msg.value, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange ETH to HAV while insisting on a particular set of rates. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rates. * @param guaranteedEtherRate The ether exchange rate which must be honored or the call will revert. * @param guaranteedHavvenRate The havven exchange rate which must be honored or the call will revert. */ function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate) public payable pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedEtherRate == usdToEthPrice); require(guaranteedHavvenRate == usdToHavPrice); return exchangeEtherForHavvens(); } /** * @notice Exchange nUSD for Havvens * @param nominAmount The amount of nomins the user wishes to exchange. */ function exchangeNominsForHavvens(uint nominAmount) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { // How many Havvens are they going to be receiving? uint havvensToSend = havvensReceivedForNomins(nominAmount); // Ok, transfer the Nomins to our address. nomin.transferFrom(msg.sender, this, nominAmount); // And send them the Havvens. havven.transfer(msg.sender, havvensToSend); emit Exchange("nUSD", nominAmount, "HAV", havvensToSend); return havvensToSend; } /** * @notice Exchange nUSD for Havvens while insisting on a particular rate. This allows a user to * exchange while protecting against frontrunning by the contract owner on the exchange rate. * @param nominAmount The amount of nomins the user wishes to exchange. * @param guaranteedRate A rate (havven price) the caller wishes to insist upon. */ function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate) public pricesNotStale notPaused returns (uint) // Returns the number of Havvens (HAV) received { require(guaranteedRate == usdToHavPrice); return exchangeNominsForHavvens(nominAmount); } /** * @notice Allows the owner to withdraw havvens from this contract if needed. * @param amount The amount of havvens to attempt to withdraw (in 18 decimal places). */ function withdrawHavvens(uint amount) external onlyOwner { havven.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /** * @notice Withdraw nomins: Allows the owner to withdraw nomins from this contract if needed. * @param amount The amount of nomins to attempt to withdraw (in 18 decimal places). */ function withdrawNomins(uint amount) external onlyOwner { nomin.transfer(owner, amount); // We don&#39;t emit our own events here because we assume that anyone // who wants to watch what the Issuance Controller is doing can // just watch ERC20 events from the Nomin and/or Havven contracts // filtered to our address. } /* ========== VIEWS ========== */ /** * @notice Check if the prices haven&#39;t been updated for longer than the stale period. */ function pricesAreStale() public view returns (bool) { return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now; } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of nomins. * @param amount The amount of nomins (in 18 decimal places) you want to ask about */ function havvensReceivedForNomins(uint amount) public view returns (uint) { // How many nomins would we receive after the transfer fee? uint nominsReceived = nomin.amountReceived(amount); // And what would that be worth in havvens based on the current price? return safeDiv_dec(nominsReceived, usdToHavPrice); } /** * @notice Calculate how many havvens you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function havvensReceivedForEther(uint amount) public view returns (uint) { // How much is the ETH they sent us worth in nUSD (ignoring the transfer fee)? uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice); // Now, how many HAV will that USD amount buy? return havvensReceivedForNomins(valueSentInNomins); } /** * @notice Calculate how many nomins you will receive if you transfer * an amount of ether. * @param amount The amount of ether (in wei) you want to ask about */ function nominsReceivedForEther(uint amount) public view returns (uint) { // How many nomins would that amount of ether be worth? uint nominsTransferred = safeMul_dec(amount, usdToEthPrice); // And how many of those would you receive after a transfer (deducting the transfer fee) return nomin.amountReceived(nominsTransferred); } /* ========== MODIFIERS ========== */ modifier onlyOracle { require(msg.sender == oracle, "Must be oracle to perform this action"); _; } modifier pricesNotStale { require(!pricesAreStale(), "Prices must not be stale to perform this action"); _; } /* ========== EVENTS ========== */ event FundsWalletUpdated(address newFundsWallet); event OracleUpdated(address newOracle); event NominUpdated(Nomin newNominContract); event HavvenUpdated(Havven newHavvenContract); event PriceStalePeriodUpdated(uint priceStalePeriod); event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent); event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount); }
* @notice Recompute and return the given account&#39;s last average balance./
function recomputeLastAverageBalance(address account) external returns (uint) { updateIssuanceData(account, nominsIssued[account], nomin.totalSupply()); return issuanceData[account].lastAverageBalance; }
2,140,192
[ 1, 426, 9200, 471, 327, 326, 864, 2236, 10, 5520, 31, 87, 1142, 8164, 11013, 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 ]
[ 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, 30067, 3024, 17115, 13937, 12, 2867, 2236, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 1089, 7568, 89, 1359, 751, 12, 4631, 16, 12457, 2679, 7568, 5957, 63, 4631, 6487, 12457, 267, 18, 4963, 3088, 1283, 10663, 203, 3639, 327, 3385, 89, 1359, 751, 63, 4631, 8009, 2722, 17115, 13937, 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 ]
./full_match/1313161554/0x90C6B69383695b4Dc4125ca010C61f78dff93fb0/sources/contracts/UTTProxy.sol
* Id for oracle jobs from this contract */
bytes32 public jobId;
13,234,570
[ 1, 548, 364, 20865, 6550, 628, 333, 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, 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, 1731, 1578, 1071, 13845, 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 "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ // Constants uint8 private constant MULTIPARTY_SIGN_THRESHOLD = 4; uint256 private constant MAX_INSURANCE = 1 ether; uint256 private constant EXPECTED_FUNDING_AMOUNT = 10 ether; address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Airline{ string name; address walletAddress; bool isRegistered; uint256 funds; bool isFunded; uint256 votes; } uint256 private airlinesCount; // How many airlines Have been registered or stored. uint256 public registeredAirlinesCount; // How many airlines have ben registered. mapping(address => Airline) public airlines; //All airlines address[] private registeredAirlines; // Array of registered airlines. // airlineAddress => voterAirlineAddress => true means the voterAirlineAddress has voted for airlineAddress. // Used to track which airlines have voted for which. mapping(address => mapping(address => bool)) private votesTracker; struct Flight { address airlineAddress; string airlineName; uint256 departureTimestamp; string flightNumber; string departureLocation; uint8 statusCode; } mapping(string => Flight) private flights; //flights struct Passenger { address passengerAddress; uint256 credit; } // Maps a passengerAddress to a mapping (=>) that contains flightCode => amount of Insurance paid // This keeps track of which passenger has booked which flights. If true then address has booked the flight, if false then it has not. mapping(address => mapping(string => uint256)) private flightBookings; mapping(address => Passenger) private passengers; address[] public passengerAddresses; // contracts which are allowed to access this contract. mapping(address => bool) private authorizedContracts; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner * Register the first airline. */ constructor() public { contractOwner = msg.sender; airlinesCount = 0; authorizedContracts[msg.sender] = true; airlines[msg.sender] = Airline ({ name: "BlockchainDev Air", walletAddress: msg.sender, isRegistered: true, funds: 10 ether, isFunded: true, votes: 0 }); registeredAirlines.push(msg.sender); airlinesCount++; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational."); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner."); _; } /** * @dev Modifier that requires the "ContractOwner" account to the same as the 'specifiedAddress' parameter. */ modifier requireAddressIsContractOwner(address specifiedAddress) { require(specifiedAddress == contractOwner, "Address is not contract owner."); _; } /** * @dev Modifier that requires 'theAddress' to be authorized */ modifier requireAddressAuthorized(address theAddress){ require(isAuthorized(theAddress), "Address is not authorized to use this contract."); _; } /** * @dev Modifier that requires 'airlineAddress' to be stored. */ modifier requireAirlineStored(address airlineAddress){ require(airlineStored(airlineAddress), "Airline address has not been stored and is not known."); _; } /** * @dev Modifier that requires 'airlineAddress' NOT be stored. */ modifier requireAirlineNotStored(address airlineAddress){ require(!airlineStored(airlineAddress), "Airline address has already been stored."); _; } /** * @dev Modifier that requires 'airlineAddress' to be registered. */ modifier requireAirlineRegistered(address airlineAddress) { require(isAirlineRegistered(airlineAddress), "Airline is not registered."); _; } /** * @dev Modifier that requires the address is non-zero. */ modifier requireValidAddress(address theAddress) { require(theAddress != address(0), "Airline address must be a non-zero."); _; } /** * @dev Modifier that requires 'airlineAddress' to NOT be registered. */ modifier requireAirlineNotRegistered(address airlineAddress) { require(!isAirlineRegistered(airlineAddress), "Airline is already registered."); _; } /** * @dev Modifier that requires that 'voterAddress' has not voted for 'airlineAddress' */ modifier requireVoterNotVotedForAirline(address voterAddress, address airlineAddress) { require(!alreadyVotedForAirline(voterAddress, airlineAddress), "Voter has voted for this airline already."); _; } /** * @dev Modifier that requires 'airlineAddress' to have provided funding of at least 10 ether. */ modifier requireAirlineHasProvidedFunding(address airlineAddress) { require(airlineProvidedFunding(airlineAddress), "Airline has not provided their fair share of funds."); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Has Airline provided their funding? * * @return A boolean value that represents if the voterAddress has already voted for the airlineAddress. */ function isContractOwner(address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return airlineAddress == contractOwner; } /** * @dev Has Airline provided their funding? * * @return A boolean value that represents if the voterAddress has already voted for the airlineAddress. */ function airlineProvidedFunding(address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return airlines[airlineAddress].funds >= EXPECTED_FUNDING_AMOUNT; } /** * @dev Has voterAddress aready voted for airlineAddress * * @return A boolean value that represents if the voterAddress has already voted for the airlineAddress. */ function alreadyVotedForAirline(address voterAddress, address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return votesTracker[airlineAddress][voterAddress] == true; } /** * @dev IS the airline registered * * @return A bool that represents if the airline is registered or not. */ function isAirlineRegistered(address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return airlines[airlineAddress].isRegistered; } /** * @dev Is the airline stored * * @return A bool that represents if the airline is stored or not. */ function airlineStored(address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return airlines[airlineAddress].walletAddress != address(0); } /** * @dev Is the address specified authorized to use this contract?. * * @return A bool that represents if the address is authorized or not. */ function isAuthorized(address contractAddress) public view requireIsOperational returns(bool) { return authorizedContracts[contractAddress] == true; } /** * @dev Is the flightCode already registered with an airline?. * * @return A bool that represents if the flightCode is already registered with an airline. */ function flightExists(string flightNumber) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return flights[flightNumber].airlineAddress != address(0); } /** * @dev Has passengerAddress already paid insurance on this flight. * * @return A bool that represents if the flightCode is already registered with an airline. */ function insurancePaid(address passengerAddress, string flightNumber) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return flightBookings[passengerAddress][flightNumber] != 0; } /** * @dev Does the passenger have ancy credit?. * * @return A bool that represents if the flightCode is already registered with an airline. */ function passengerHasCredit(address passengerAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return passengers[passengerAddress].credit > 0; } /** * @dev Passenger Exists. * * @return A bool that represents whether a passenger has bought insurance. */ function passengerExists(address passengerAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return passengers[passengerAddress].passengerAddress != address(0); } /** * @dev Passenger Paid Insurance for flight?. * * @return A bool that represents whether a passenger has bought insurance for specific flight. */ function passengerPaidInsuranceForFlight(address passengerAddress, string flightNumber) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { return flightBookings[passengerAddress][flightNumber] > 0 ; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Authorize the specified address * */ function authorizeCaller(address contractAddress) public requireIsOperational requireContractOwner { authorizedContracts[contractAddress] = true; } /** * @dev Deauthorize the contract */ function deauthorizeCaller(address contractAddress)external requireContractOwner { delete authorizedContracts[contractAddress]; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airlineAddress, string airlineName, address registererAddress) external requireAddressAuthorized(msg.sender) returns (bool success) { success = false; if (airlinesCount < MULTIPARTY_SIGN_THRESHOLD){ airlines[airlineAddress] = Airline({ name: airlineName, walletAddress: airlineAddress, isRegistered: true, funds: 0, isFunded: false, votes: 1}); registeredAirlines.push(airlineAddress); airlinesCount++; registeredAirlinesCount++; success = true; }else{ airlines[airlineAddress] = Airline({ name: airlineName, walletAddress: airlineAddress, isRegistered: false, funds: 0, isFunded: false, votes: 0}); airlinesCount++; vote(airlineAddress, registererAddress); } return (success); } /** * @dev Get the information for the airline at the specified index. * */ function getAirlineInfo(uint256 index) public view requireIsOperational requireAddressAuthorized(msg.sender) returns(address airlineAddress, string airlineName) { airlineAddress = registeredAirlines[index]; airlineName = airlines[airlineAddress].name; } function getAirlineFunding(address airlineAddress) public view requireAddressAuthorized(msg.sender) returns(uint256) { return airlines[airlineAddress].funds; } function getAirlinesCount() public view requireAddressAuthorized(msg.sender) returns(uint256) { return airlinesCount; } function getAirlineName(address airlineAddress) public view requireAddressAuthorized(msg.sender) requireAirlineRegistered(airlineAddress) returns(string) { return airlines[airlineAddress].name; } function getAirlineIsRegistered(address airlineAddress) public view requireAddressAuthorized(msg.sender) returns(bool) { return airlines[airlineAddress].isRegistered; } /** * @dev Vote to register the new airline * */ function vote(address airlineAddress, address voterAddress) public requireIsOperational requireAddressAuthorized(msg.sender) { airlines[airlineAddress].votes++; votesTracker[airlineAddress][voterAddress] = true; if (airlines[airlineAddress].votes >= registeredAirlinesCount.div(2)){ airlines[airlineAddress].isRegistered = true; registeredAirlines.push(airlineAddress); registeredAirlinesCount++; } } /** * @dev Get number of votes for an airline * */ function getVoteCount(address airlineAddress) public view requireIsOperational requireAddressAuthorized(msg.sender) requireAirlineStored(airlineAddress) returns(uint256) { return airlines[airlineAddress].votes; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining */ function fundAirline(address airlineAddress, uint256 amountInWei) external payable requireIsOperational requireAddressAuthorized(msg.sender) { airlines[airlineAddress].funds = airlines[airlineAddress].funds.add(amountInWei); if (airlines[airlineAddress].funds >= EXPECTED_FUNDING_AMOUNT){ airlines[airlineAddress].isFunded = true; } if (msg.value > amountInWei){ uint256 amountToReturn = msg.value.sub(amountInWei); airlineAddress.transfer(amountToReturn); } } /** * @dev Register a flight to an airline. * */ function registerFlight(address airlineAddress, uint256 departureTimestamp, string flightNumber, string destination, uint8 statusCode) external requireAddressAuthorized(msg.sender) returns(bool success) { success = false; flights[flightNumber] = Flight({ airlineAddress: airlineAddress, airlineName: airlines[airlineAddress].name, departureTimestamp: departureTimestamp, flightNumber: flightNumber, departureLocation: destination, statusCode: statusCode }); success =true; //flightsCount++; return success; } // Query the status of any flight function retrieveFlightStatus(string flightNumber) external view requireAddressAuthorized(msg.sender) returns(uint8) { return flights[flightNumber].statusCode; } /** * @dev Update the status code for a given flight. * */ function updateFlightStatusCode(string flightNumber, uint8 statusCode) external requireAddressAuthorized(msg.sender) { flights[flightNumber].statusCode = statusCode; } /** * @dev Update the timestamp for a given flight. * */ function updateFlightTimestamp(string flightNumber, uint256 timestamp) external requireAddressAuthorized(msg.sender) { flights[flightNumber].departureTimestamp = timestamp; } /** * @dev passengerAddress buys insurance for flightCode * */ function buyInsurance(address passengerAddress, string flightNumber) external payable requireAddressAuthorized(msg.sender) { if (passengers[passengerAddress].passengerAddress == address(0)){ passengerAddresses.push(passengerAddress); passengers[passengerAddress] = Passenger({ passengerAddress: passengerAddress, credit: 0 }); } if (msg.value > MAX_INSURANCE){ flightBookings[passengerAddress][flightNumber] = MAX_INSURANCE; uint256 excess = msg.value.sub(MAX_INSURANCE); passengerAddress.transfer(excess); }else{ flightBookings[passengerAddress][flightNumber] = msg.value; } } /** * @dev Credit payouts to insurees */ function creditInsurees(string flightNumber) external requireIsOperational requireAddressAuthorized(msg.sender) returns(bool) { for (uint i = 0; i < passengerAddresses.length; i++) { if(flightBookings[passengerAddresses[i]][flightNumber] != 0) { uint256 currentCredit = passengers[passengerAddresses[i]].credit; uint256 insurenceAmountPaid = flightBookings[passengerAddresses[i]][flightNumber]; flightBookings[passengerAddresses[i]][flightNumber] = 0; uint256 firstHalf = insurenceAmountPaid.div(2); uint256 amountToPay = insurenceAmountPaid.add(firstHalf); passengers[passengerAddresses[i]].credit = currentCredit.add(amountToPay);// + amountToPay ; } } return true; } /* * @dev Get the amount of credit the passenger has. * */ function getCreditForPassenger(address passengerAddress) external view requireIsOperational requireAddressAuthorized(msg.sender) returns (uint256) { return passengers[passengerAddress].credit; } /** * @dev Transfers eligible payout funds to insuree * */ //TODO: When this is confirmed to be working, add support for the passenger to specify an amount to be withdrawn. function withdraw(address passengerAddress) external payable requireIsOperational requireAddressAuthorized(msg.sender) { uint256 contractBalance = address(this).balance; uint256 credit = passengers[passengerAddress].credit; //TODO: Move this into a modifier? require(contractBalance > credit, "The contract does not have enough funds to pay the credit"); passengers[passengerAddress].credit = 0; passengerAddress.transfer(credit); } /** * @dev Transfers eligible payout funds to insuree * */ function pay() external pure {} /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund() public payable {} function getFlightKey( address airline, string memory flight, uint256 timestamp ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
* @dev Sets contract operations on/off When operational mode is disabled, all write transactions except for this one will fail/
function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; }
5,512,528
[ 1, 2785, 6835, 5295, 603, 19, 3674, 5203, 1674, 287, 1965, 353, 5673, 16, 777, 1045, 8938, 1335, 364, 333, 1245, 903, 2321, 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 ]
[ 1, 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 ]
[ 1, 565, 445, 444, 3542, 1776, 1482, 12, 6430, 1965, 13, 3903, 7010, 3639, 2583, 8924, 5541, 288, 203, 3639, 1674, 287, 273, 1965, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-09 */ /** *Submitted for verification at BscScan.com on 2021-03-08 */ // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/oracle/oracle.sol pragma solidity 0.6.12; /** * @title BiFi's mockup Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract observerOracle is Modifier { address payable owner; mapping(address => bool) operators; int256 price; modifier onlyOwner { require(msg.sender == owner, "onlyOwner"); _; } modifier onlyOperators { address sender = msg.sender; require(operators[sender] || sender == owner, "onlyOperators"); _; } constructor (int256 _price) public { address payable sender = msg.sender; owner = sender; operators[sender] = true; price = _price; } function ownershipTransfer(address payable _owner) onlyOwner external returns (bool) { owner = _owner; return true; } function setOperator(address payable addr, bool flag) onlyOwner external returns (bool) { operators[addr] = flag; return flag; } function latestAnswer() external view returns (int256) { return price; } function setPrice(int256 _price) onlyOwner public { price = _price; } }
* @title BiFi's mockup Contract @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)/
contract observerOracle is Modifier { address payable owner; mapping(address => bool) operators; int256 price; modifier onlyOwner { require(msg.sender == owner, "onlyOwner"); _; } modifier onlyOperators { address sender = msg.sender; require(operators[sender] || sender == owner, "onlyOperators"); _; } constructor (int256 _price) public { address payable sender = msg.sender; owner = sender; operators[sender] = true; price = _price; } function ownershipTransfer(address payable _owner) onlyOwner external returns (bool) { owner = _owner; return true; } function setOperator(address payable addr, bool flag) onlyOwner external returns (bool) { operators[addr] = flag; return flag; } function latestAnswer() external view returns (int256) { return price; } function setPrice(int256 _price) onlyOwner public { price = _price; } }
7,740,056
[ 1, 18808, 42, 77, 1807, 5416, 416, 13456, 225, 16682, 42, 77, 12, 307, 267, 4811, 20651, 2947, 16, 490, 24462, 17, 79, 79, 16, 268, 4801, 79, 72, 75, 407, 21, 16, 302, 932, 24083, 61, 5161, 13176, 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, 16351, 9655, 23601, 353, 12832, 288, 203, 225, 1758, 8843, 429, 3410, 31, 203, 225, 2874, 12, 2867, 516, 1426, 13, 12213, 31, 203, 203, 225, 509, 5034, 6205, 31, 203, 203, 203, 202, 20597, 1338, 5541, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3700, 5541, 8863, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 24473, 288, 203, 202, 202, 2867, 5793, 273, 1234, 18, 15330, 31, 203, 202, 202, 6528, 12, 30659, 63, 15330, 65, 747, 5793, 422, 3410, 16, 315, 3700, 24473, 8863, 203, 202, 202, 67, 31, 203, 202, 97, 203, 203, 202, 12316, 261, 474, 5034, 389, 8694, 13, 1071, 203, 202, 95, 203, 202, 202, 2867, 8843, 429, 5793, 273, 1234, 18, 15330, 31, 203, 202, 202, 8443, 273, 5793, 31, 203, 202, 202, 30659, 63, 15330, 65, 273, 638, 31, 203, 202, 202, 8694, 273, 389, 8694, 31, 203, 202, 97, 203, 203, 202, 915, 23178, 5912, 12, 2867, 8843, 429, 389, 8443, 13, 1338, 5541, 3903, 1135, 261, 6430, 13, 288, 203, 202, 202, 8443, 273, 389, 8443, 31, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 202, 915, 444, 5592, 12, 2867, 8843, 429, 3091, 16, 1426, 2982, 13, 1338, 5541, 3903, 1135, 261, 6430, 13, 288, 203, 202, 202, 30659, 63, 4793, 65, 273, 2982, 31, 203, 202, 202, 2463, 2982, 31, 203, 202, 97, 203, 202, 915, 4891, 13203, 1435, 3903, 1476, 1135, 261, 474, 5034, 13, 203, 202, 95, 2 ]
pragma solidity 0.7.6; import "./_external/SafeMath.sol"; import "./_external/Ownable.sol"; import "./lib/SafeMathInt.sol"; import "./lib/UInt256Lib.sol"; interface IUFragments { function totalSupply() external view returns (uint256); function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); } interface IOracle { function getData() external returns (uint256, bool); } /** * @title uFragments Monetary Supply Policy * @dev This is an implementation of the uFragments Ideal Money protocol. * uFragments operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the uFragments ERC20 token in response to * market oracles. */ contract UFragmentsPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); IUFragments public uFrags; // Provides the current CPI, as an 18 decimal fixed point number. IOracle public cpiOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 Ample is trading for $1.50. IOracle public marketOracle; // CPI value at the time of launch, as an 18 decimal fixed point number. uint256 private baseCpi; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = uint256(type(int256).max) / MAX_RATE; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < block.timestamp); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = block .timestamp .sub(block.timestamp.mod(minRebaseTimeIntervalSec)) .add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 cpi; bool cpiValid; (cpi, cpiValid) = cpiOracle.getData(); require(cpiValid); uint256 targetRate = cpi.mul(10**DECIMALS).div(baseCpi); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, block.timestamp); } /** * @notice Sets the reference to the CPI oracle. * @param cpiOracle_ The address of the cpi oracle contract. */ function setCpiOracle(IOracle cpiOracle_) external onlyOwner { cpiOracle = cpiOracle_; } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_ ) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @notice A multi-chain AMPL interface method. The Ampleforth monetary policy contract * on the base-chain and XC-AmpleController contracts on the satellite-chains * implement this method. It atomically returns two values: * what the current contract believes to be, * the globalAmpleforthEpoch and globalAMPLSupply. * @return globalAmpleforthEpoch The current epoch number. * @return globalAMPLSupply The total supply at the current epoch. */ function globalAmpleforthEpochAndAMPLSupply() external view returns (uint256, uint256) { return (epoch, uFrags.totalSupply()); } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize( address owner_, IUFragments uFrags_, uint256 baseCpi_ ) public initializer { Ownable.initialize(owner_); // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 5 * 10**(DECIMALS - 2); rebaseLag = 30; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; uFrags = uFrags_; baseCpi = baseCpi_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return uFrags.totalSupply().toInt256Safe().mul(rate.toInt256Safe().sub(targetRateSigned)).div( targetRateSigned ); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold).div(10**DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } pragma solidity 0.7.6; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity 0.7.6; import "./Initializable.sol"; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Initializable { address private _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. */ function initialize(address sender) public virtual initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit 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; } uint256[50] private ______gap; } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.7.6; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails 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)); return c; } /** * @dev Adds two int256 variables and fails 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)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } pragma solidity 0.7.6; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } pragma solidity 0.7.6; /** * @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 wasInitializing = initializing; initializing = true; initialized = true; _; initializing = wasInitializing; } /// @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. // MINOR CHANGE HERE: // previous code // uint256 cs; // assembly { cs := extcodesize(address) } // return cs == 0; // current code 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; }
* @return If the latest block timestamp is within the rebase time window it, returns true. Otherwise, returns false./
function inRebaseWindow() public view returns (bool) { return (block.timestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && block.timestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))); }
225,742
[ 1, 2463, 971, 326, 4891, 1203, 2858, 353, 3470, 326, 283, 1969, 813, 2742, 518, 16, 1135, 638, 18, 540, 5272, 16, 1135, 629, 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 ]
[ 1, 1, 1, 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, 316, 426, 1969, 3829, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 2629, 18, 5508, 18, 1711, 12, 1154, 426, 1969, 950, 4006, 2194, 13, 1545, 283, 1969, 3829, 2335, 2194, 597, 203, 5411, 1203, 18, 5508, 18, 1711, 12, 1154, 426, 1969, 950, 4006, 2194, 13, 411, 203, 5411, 261, 266, 1969, 3829, 2335, 2194, 18, 1289, 12, 266, 1969, 3829, 1782, 2194, 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 ]
pragma solidity ^0.4.23; contract Events { event onGiveKeys( address addr, uint256 keys ); event onShareOut( uint256 dividend ); } contract Referral is Events { using SafeMath for *; //============================================================================== // modifier //============================================================================== modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } //============================================================================== // config //============================================================================== string public name = "PTReferral"; string public symbol = "PT7Dα"; uint256 constant internal magnitude = 1e18; //============================================================================== // dataset //============================================================================== uint256 public pID_ = 0; uint256 public keySupply_ = 0; mapping(address => uint256) public pIDxAddr_; mapping(uint256 => address) public AddrxPID_; mapping(bytes32 => bool) public administrators; mapping(address => uint256) public keyBalanceLedger_; //============================================================================== // public functions //============================================================================== constructor() public { administrators[0x14c319c3c982350b442e4074ec4736b3ac376ebdca548bdda0097040223e7bd6] = true; } //============================================================================== // private functions //============================================================================== function getPlayerID(address addr) private returns (uint256) { uint256 _pID = pIDxAddr_[addr]; if (_pID == 0) { pID_++; _pID = pID_; pIDxAddr_[addr] = _pID; AddrxPID_[_pID] = addr; } return (_pID); } //============================================================================== // external functions //============================================================================== // profits from other contracts function outerDividend() external payable { } //============================================================================== // administrator only functions //============================================================================== function setAdministrator(bytes32 _identifier, bool _status) public onlyAdministrator() { administrators[_identifier] = _status; } function setName(string _name) public onlyAdministrator() { name = _name; } function setSymbol(string _symbol) public onlyAdministrator() { symbol = _symbol; } function giveKeys(address _toAddress, uint256 _amountOfkeys) public onlyAdministrator() returns(bool) { getPlayerID(_toAddress); keySupply_ = keySupply_.add(_amountOfkeys); keyBalanceLedger_[_toAddress] = keyBalanceLedger_[_toAddress].add(_amountOfkeys); emit onGiveKeys(_toAddress, _amountOfkeys); return true; } function shareOut(uint256 _dividend) public onlyAdministrator() { require(_dividend <= this.balance,"exceeded the maximum"); if (keySupply_ > 0) { for (uint256 i = 1; i <= pID_; i++) { address _addr = AddrxPID_[i]; _addr.transfer(keyBalanceLedger_[_addr].mul(_dividend).div(keySupply_)); } emit onShareOut(_dividend); } } //============================================================================== // view only functions //============================================================================== function totalEthereumBalance() public view returns(uint) { return this.balance; } } library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } 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); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } 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); } } }
============================================================================== modifier==============================================================================
contract Referral is Events { using SafeMath for *; modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } string public symbol = "PT7Dα"; uint256 constant internal magnitude = 1e18; uint256 public keySupply_ = 0; mapping(address => uint256) public pIDxAddr_; mapping(uint256 => address) public AddrxPID_; mapping(bytes32 => bool) public administrators; mapping(address => uint256) public keyBalanceLedger_; public string public name = "PTReferral"; uint256 public pID_ = 0; constructor() { administrators[0x14c319c3c982350b442e4074ec4736b3ac376ebdca548bdda0097040223e7bd6] = true; } function getPlayerID(address addr) private returns (uint256) { uint256 _pID = pIDxAddr_[addr]; if (_pID == 0) { pID_++; _pID = pID_; pIDxAddr_[addr] = _pID; AddrxPID_[_pID] = addr; } return (_pID); } function getPlayerID(address addr) private returns (uint256) { uint256 _pID = pIDxAddr_[addr]; if (_pID == 0) { pID_++; _pID = pID_; pIDxAddr_[addr] = _pID; AddrxPID_[_pID] = addr; } return (_pID); } function outerDividend() external payable { } function setAdministrator(bytes32 _identifier, bool _status) public onlyAdministrator() { administrators[_identifier] = _status; } function setName(string _name) public onlyAdministrator() { name = _name; } function setSymbol(string _symbol) public onlyAdministrator() { symbol = _symbol; } function giveKeys(address _toAddress, uint256 _amountOfkeys) public onlyAdministrator() returns(bool) { getPlayerID(_toAddress); keySupply_ = keySupply_.add(_amountOfkeys); keyBalanceLedger_[_toAddress] = keyBalanceLedger_[_toAddress].add(_amountOfkeys); emit onGiveKeys(_toAddress, _amountOfkeys); return true; } function shareOut(uint256 _dividend) public onlyAdministrator() { require(_dividend <= this.balance,"exceeded the maximum"); if (keySupply_ > 0) { for (uint256 i = 1; i <= pID_; i++) { address _addr = AddrxPID_[i]; _addr.transfer(keyBalanceLedger_[_addr].mul(_dividend).div(keySupply_)); } emit onShareOut(_dividend); } } function shareOut(uint256 _dividend) public onlyAdministrator() { require(_dividend <= this.balance,"exceeded the maximum"); if (keySupply_ > 0) { for (uint256 i = 1; i <= pID_; i++) { address _addr = AddrxPID_[i]; _addr.transfer(keyBalanceLedger_[_addr].mul(_dividend).div(keySupply_)); } emit onShareOut(_dividend); } } function shareOut(uint256 _dividend) public onlyAdministrator() { require(_dividend <= this.balance,"exceeded the maximum"); if (keySupply_ > 0) { for (uint256 i = 1; i <= pID_; i++) { address _addr = AddrxPID_[i]; _addr.transfer(keyBalanceLedger_[_addr].mul(_dividend).div(keySupply_)); } emit onShareOut(_dividend); } } function totalEthereumBalance() public view returns(uint) { return this.balance; } }
2,545,418
[ 1, 9917, 26678, 282, 9606, 9917, 26678, 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, 3941, 29084, 353, 9043, 288, 203, 565, 1450, 14060, 10477, 364, 380, 31, 203, 203, 565, 9606, 1338, 4446, 14207, 1435, 95, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 7010, 3639, 2583, 12, 3666, 3337, 3062, 63, 79, 24410, 581, 5034, 24899, 10061, 1887, 13, 19226, 203, 3639, 389, 31, 203, 565, 289, 203, 565, 533, 1071, 3273, 273, 315, 1856, 27, 40, 143, 114, 14432, 203, 565, 2254, 5034, 5381, 2713, 13463, 273, 404, 73, 2643, 31, 203, 565, 2254, 5034, 1071, 498, 3088, 1283, 67, 273, 374, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 293, 734, 92, 3178, 67, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 10216, 92, 16522, 67, 31, 203, 565, 2874, 12, 3890, 1578, 516, 1426, 13, 1071, 30162, 3062, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 498, 13937, 28731, 67, 31, 203, 3639, 1071, 203, 565, 533, 1071, 508, 273, 315, 1856, 1957, 29084, 14432, 203, 565, 2254, 5034, 1071, 293, 734, 67, 273, 374, 31, 203, 565, 3885, 1435, 203, 565, 288, 203, 3639, 30162, 3062, 63, 20, 92, 3461, 71, 23, 3657, 71, 23, 71, 10689, 4366, 3361, 70, 6334, 22, 73, 7132, 5608, 557, 9462, 5718, 70, 23, 1077, 6418, 26, 73, 16410, 5353, 6564, 28, 70, 449, 69, 713, 10580, 3028, 3103, 4366, 73, 27, 16410, 26, 65, 273, 638, 31, 203, 565, 289, 203, 565, 445, 1689, 6363, 734, 12, 2867, 3091, 13, 203, 3639, 2 ]
./partial_match/1/0x3231Cb76718CDeF2155FC47b5286d82e6eDA273f/sources/EUR.sol
* @dev Mints new tokens. @param to Address to credit the tokens. @param amount Number of tokens to mint./
function mintTo(address to, uint amount) external returns (bool ok) { ok = controller.mintTo_withCaller(msg.sender, to, amount); emit Transfer(0x0, to, amount); }
3,732,646
[ 1, 49, 28142, 394, 2430, 18, 225, 358, 5267, 358, 12896, 326, 2430, 18, 225, 3844, 3588, 434, 2430, 358, 312, 474, 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 ]
[ 1, 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 ]
[ 1, 565, 445, 312, 474, 774, 12, 2867, 358, 16, 2254, 3844, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 1529, 13, 203, 565, 288, 203, 3639, 1529, 273, 2596, 18, 81, 474, 774, 67, 1918, 11095, 12, 3576, 18, 15330, 16, 358, 16, 3844, 1769, 203, 3639, 3626, 12279, 12, 20, 92, 20, 16, 358, 16, 3844, 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 ]
pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '../interfaces/ISimpleERCFund.sol'; import '../owner/AdminRole.sol'; import '../utils/ContractGuard.sol'; import '../wrapper/PEGWrapper.sol'; contract SPool is PEGWrapper, ContractGuard{ uint256 public stake_duration; uint256 public starttime; uint256 public times = 0; uint256 public dailyReward; address public fund; address public cash; bool public once = true; /// @notice 结构体:SPool席位 struct SPoolseat { uint256 lastSnapshotIndex; // 最后快照索引 uint256 rewardEarned; // 未领取的奖励数量 } /// @notice 结构体:SPool快照 struct SPoolSnapshot { uint256 time; // 区块高度 uint256 rewardReceived; // 收到的奖励 uint256 rewardPerPeg; // 每股奖励数量 } constructor( address _cash, address _peg, address _fund, uint256 _reward, uint256 _stake_duration, uint256 _starttime ) public { cash = _cash; peg = IERC20(_peg); starttime = _starttime; dailyReward = _reward; stake_duration = _stake_duration; fund = _fund; // 创建SPool快照 SPoolSnapshot memory genesisSnapshot = SPoolSnapshot({ time: block.number, rewardReceived: 0, rewardPerPeg: 0 }); //SPool的创世快照推入数组 SPoolHistory.push(genesisSnapshot); } mapping(address => SPoolseat) private investors; /// @dev spool快照 SPoolSnapshot[] private SPoolHistory; /* ========== Modifiers =============== */ /// @notice 修饰符:需要调用者抵押数量大于0 modifier investorExists { require( balanceOf(msg.sender) > 0, 'sFUND: The investor does not exist' ); _; } modifier updateReward(address investor) { // 如果成员地址不是0地址 if (investor != address(0)) { // 根据成员地址实例化SPool席位 SPoolseat memory seat = investors[investor]; // 已获取奖励数量 = 计算可提取的总奖励 seat.rewardEarned = earned(investor); // 最后快照索引 = SPool快照数组长度-1 seat.lastSnapshotIndex = latestSnapshotIndex(); // 重新赋值 investors[investor] = seat; } _; } function latestSnapshotIndex() public view returns (uint256) { // SPool数组长度-1 return SPoolHistory.length.sub(1); } function getLatestSnapshot() internal view returns (SPoolSnapshot memory) { return SPoolHistory[latestSnapshotIndex()]; } function getLastSnapshotIndexOf(address investor) public view returns (uint256) { return investors[investor].lastSnapshotIndex; } function getLastSnapshotOf(address investor) internal view returns (SPoolSnapshot memory) { return SPoolHistory[getLastSnapshotIndexOf(investor)]; } function rewardPerPeg() public view returns (uint256) { return getLatestSnapshot().rewardPerPeg; } function earned(address investor) public view returns (uint256) { uint256 latestRPS = rewardPerPeg(); uint256 storedRPS = getLastSnapshotOf(investor).rewardPerPeg; return balanceOf(investor).mul(latestRPS.sub(storedRPS)).div(1e18).add( investors[investor].rewardEarned ); } function stake(uint256 amount) public override onlyOneBlock { require(amount > 0, 'SPool: Cannot stake 0'); require(block.timestamp >= starttime, 'SPool: not start'); require(block.timestamp < starttime + stake_duration, 'SPool: stake end'); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public override { require(0 > 1, "unable to withdraw"); } function exit() external { getReward(); } function getReward() public updateReward(msg.sender) { //更新SPool的奖励后,获取奖励数量 uint256 reward = investors[msg.sender].rewardEarned; // 如果数量大于0 if (reward > 0) { //把未领取的奖励数量重设为0 investors[msg.sender].rewardEarned = 0; // 将奖励发送给用户 IERC20(cash).safeTransfer(msg.sender, reward); //触发完成奖励事件 emit RewardPaid(msg.sender, reward); } } function release(uint256 amount) external onlyOneBlock onlyAdmin { require(once, 'SPool: release err'); // 确认分配数量大于0 require(amount > 0, 'SPoolroom: Cannot allocate 0'); // 确认质押总量大于0 require( totalSupply() > 0, 'SPoolroom: Cannot allocate when totalSupply is 0' ); uint256 prevRPS = rewardPerPeg(); uint256 nextRPS = prevRPS.add(amount.mul(10**18).div(totalSupply())); SPoolSnapshot memory newSnapshot = SPoolSnapshot({ time: block.number, // 当前区块高度 rewardReceived: amount, // 收到的分配数量 rewardPerPeg: nextRPS // 每股奖励数量 }); //更新快照推入数组 SPoolHistory.push(newSnapshot); emit RewardAdded(amount); uint256 fundamount= totalSupply(); peg.safeApprove(fund, fundamount); // 调用fund合约的存款方法存入sFUND ISimpleERCFund(fund).deposit( address(peg), fundamount, 'Treasury: Desposit Fund' ); emit DespositFund(now, fundamount); once = false; } function updateStartTime(uint256 starttime_) external onlyAdmin { starttime = starttime_; } event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event DespositFund(uint256 timestamp, uint256 fundamount); }
更新SPool的奖励后,获取奖励数量 如果数量大于0把未领取的奖励数量重设为0 将奖励发送给用户触发完成奖励事件
function getReward() public updateReward(msg.sender) { uint256 reward = investors[msg.sender].rewardEarned; if (reward > 0) { investors[msg.sender].rewardEarned = 0; IERC20(cash).safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } }
14,040,130
[ 1, 167, 254, 117, 167, 249, 113, 55, 2864, 168, 253, 231, 166, 103, 249, 166, 237, 114, 166, 243, 241, 176, 125, 239, 169, 241, 120, 166, 242, 249, 166, 103, 249, 166, 237, 114, 167, 248, 113, 170, 234, 242, 225, 166, 104, 229, 167, 257, 255, 167, 248, 113, 170, 234, 242, 166, 102, 105, 165, 123, 241, 20, 167, 237, 237, 167, 255, 108, 170, 100, 233, 166, 242, 249, 168, 253, 231, 166, 103, 249, 166, 237, 114, 167, 248, 113, 170, 234, 242, 170, 234, 240, 169, 111, 127, 165, 121, 123, 20, 225, 166, 113, 233, 166, 103, 249, 166, 237, 114, 166, 242, 244, 170, 227, 228, 168, 124, 252, 168, 247, 106, 167, 235, 120, 169, 105, 104, 166, 242, 244, 166, 111, 239, 167, 235, 243, 166, 103, 249, 166, 237, 114, 165, 123, 238, 165, 124, 119, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 445, 4170, 359, 1060, 1435, 1071, 1089, 17631, 1060, 12, 3576, 18, 15330, 13, 288, 203, 3639, 2254, 5034, 19890, 273, 2198, 395, 1383, 63, 3576, 18, 15330, 8009, 266, 2913, 41, 1303, 329, 31, 203, 3639, 309, 261, 266, 2913, 405, 374, 13, 288, 203, 5411, 2198, 395, 1383, 63, 3576, 18, 15330, 8009, 266, 2913, 41, 1303, 329, 273, 374, 31, 203, 5411, 467, 654, 39, 3462, 12, 71, 961, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 19890, 1769, 203, 5411, 3626, 534, 359, 1060, 16507, 350, 12, 3576, 18, 15330, 16, 19890, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.5; import "../utils/BlockHashRegister.sol"; import "../characters/Characters.sol"; import "../tokens/Elements.sol"; import "../tokens/Gears.sol"; import "../tokens/Rooms.sol"; import "../player/Player.sol"; contract DungeonDataLayout { struct Room { uint64 blockNumber; uint64 monsterBlockNumber; uint64 numActiveCharacters; uint8 direction; uint8 exits; uint8 kind; uint8 areaAtDiscovery; uint8 lastRoomIndex; uint8 index; uint256 discoverer; uint64 randomEvent; } struct Character { uint256 location; uint8 direction; int64 floors; uint256 slot_1; // attack // TODO store this on character NFT ? uint256 slot_2; // defense // TODO store this on character NFT ? uint256 slot_3; // accessory 1 // TODO store this on character NFT ? uint256 slot_4; // accessory 2 // TODO store this on character NFT ?5 uint256 slot_5; // accessory 3 // TODO store this on character NFT ? } struct Area { uint8 areaType; uint8 discovered; // record room types already discovered : temple, teleport ... uint8 lastRoomIndex; // track what was the index of the room discovered first in last block uint8 currentIndex; // track the index of room discovered in the same block uint256 lastRoom; // last room disovered in a block, used for area blockHash too uint64 eventBlockNumber; } mapping(uint256 => Character) _characters; mapping(uint256 => Room) _rooms; mapping(uint256 => Area) _areas; struct AreaCounter { uint64 lastPeriod; uint64 numAreas; } AreaCounter _areaCounter; address _adminContract; BlockHashRegister _blockHashRegister; Characters _charactersContract; Elements _elementsContract; Gears _gearsContract; Rooms _roomsContract; Player _playerContract; mapping(uint256 => mapping(uint256 => mapping(uint256 => bool))) _unlockedExits; struct Quest { uint8 status; string data; } mapping(uint256 => mapping(uint64 => Quest)) _quests; // _quests[character][id] mapping(address => uint256) _taxDueDate; mapping(uint256 => string) _customRoomNames; }
record room types already discovered : temple, teleport ...
uint8 discovered;
6,461,265
[ 1, 3366, 7725, 1953, 1818, 18238, 294, 1022, 1802, 16, 26855, 1372, 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, 2254, 28, 18238, 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 ]
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./interfaces/IVesting.sol"; /** * @title Vesting * @author Enjinstarter */ contract Vesting is IVesting { using SafeMath for uint256; using SafeERC20 for IERC20; struct VestingSchedule { uint256 cliffDurationDays; // Cliff duration in days with respect to the start of vesting schedule uint256 percentReleaseAtScheduleStart; // Percentage of grant amount to be released in wei at start of vesting schedule uint256 percentReleaseForEachInterval; // Percentage of grant amount to be released in wei for each interval after cliff duration uint256 intervalDays; // Vesting interval in days uint256 gapDays; // Gap between intervals in days uint256 numberOfIntervals; // Number of intervals ReleaseMethod releaseMethod; } struct VestingGrant { uint256 grantAmount; // Total number of tokens granted bool isRevocable; // true if vesting grant is revocable (a gift), false if irrevocable (purchased) bool isRevoked; // true if vesting grant has been revoked bool isActive; // true if vesting grant is active } uint256 public constant BATCH_MAX_NUM = 200; uint256 public constant PERCENT_100_WEI = 100 ether; uint256 public constant SECONDS_IN_DAY = 86400; address public governanceAccount; address public vestingAdmin; address public tokenAddress; uint256 public totalGrantAmount; uint256 public totalReleasedAmount; uint256 public scheduleStartTimestamp; bool public allowAccumulate; VestingSchedule private _vestingSchedule; mapping(address => VestingGrant) private _vestingGrants; mapping(address => uint256) private _released; constructor( address tokenAddress_, uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod, bool allowAccumulate_ ) { require(tokenAddress_ != address(0), "Vesting: zero token address"); require( percentReleaseAtScheduleStart <= PERCENT_100_WEI, "Vesting: percent release at grant start > 100%" ); require( percentReleaseForEachInterval <= PERCENT_100_WEI, "Vesting: percent release for each interval > 100%" ); require( intervalDays.add(gapDays) > 0, "Vesting: zero interval and gap" ); require( percentReleaseAtScheduleStart.add( percentReleaseForEachInterval.mul(numberOfIntervals) ) <= PERCENT_100_WEI, "Vesting: total percent release > 100%" ); governanceAccount = msg.sender; vestingAdmin = msg.sender; tokenAddress = tokenAddress_; _vestingSchedule.cliffDurationDays = cliffDurationDays; _vestingSchedule .percentReleaseAtScheduleStart = percentReleaseAtScheduleStart; _vestingSchedule .percentReleaseForEachInterval = percentReleaseForEachInterval; _vestingSchedule.intervalDays = intervalDays; _vestingSchedule.gapDays = gapDays; _vestingSchedule.numberOfIntervals = numberOfIntervals; _vestingSchedule.releaseMethod = releaseMethod; allowAccumulate = allowAccumulate_; } modifier onlyBy(address account) { require(msg.sender == account, "Vesting: sender unauthorized"); _; } /** * @dev isRevocable will be ignored if grant already added but amount allowed to accumulate. */ function addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) external override onlyBy(vestingAdmin) { _addVestingGrant(account, grantAmount, isRevocable); } function revokeVestingGrant(address account) external override onlyBy(vestingAdmin) { _revokeVestingGrant(account); } function release() external override { uint256 releasableAmount = releasableAmountFor(msg.sender); _release(msg.sender, releasableAmount); } function transferUnusedTokens() external override onlyBy(governanceAccount) { uint256 unusedAmount = IERC20(tokenAddress) .balanceOf(address(this)) .add(totalReleasedAmount) .sub(totalGrantAmount); require(unusedAmount > 0, "Vesting: nothing to transfer"); IERC20(tokenAddress).safeTransfer(governanceAccount, unusedAmount); } function addVestingGrantsBatch( address[] memory accounts, uint256[] memory grantAmounts, bool[] memory isRevocables ) external override onlyBy(vestingAdmin) { require(accounts.length > 0, "Vesting: empty"); require(accounts.length <= BATCH_MAX_NUM, "Vesting: exceed max"); require( grantAmounts.length == accounts.length, "Vesting: grant amounts length different" ); require( isRevocables.length == accounts.length, "Vesting: is revocables length different" ); for (uint256 i = 0; i < accounts.length; i++) { _addVestingGrant(accounts[i], grantAmounts[i], isRevocables[i]); } } function setScheduleStartTimestamp(uint256 scheduleStartTimestamp_) external override onlyBy(vestingAdmin) { require( scheduleStartTimestamp_ > block.timestamp, "Vesting: start before current timestamp" ); uint256 oldScheduleStartTimestamp = scheduleStartTimestamp; require( oldScheduleStartTimestamp == 0 || block.timestamp < oldScheduleStartTimestamp, "Vesting: already started" ); scheduleStartTimestamp = scheduleStartTimestamp_; emit ScheduleStartTimestampSet( msg.sender, scheduleStartTimestamp_, oldScheduleStartTimestamp ); } function setGovernanceAccount(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); governanceAccount = account; } function setVestingAdmin(address account) external override onlyBy(governanceAccount) { require(account != address(0), "Vesting: zero account"); vestingAdmin = account; } function getVestingSchedule() external view override returns ( uint256 cliffDurationDays, uint256 percentReleaseAtScheduleStart, uint256 percentReleaseForEachInterval, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod ) { VestingSchedule memory vestingSchedule = _vestingSchedule; cliffDurationDays = vestingSchedule.cliffDurationDays; percentReleaseAtScheduleStart = vestingSchedule .percentReleaseAtScheduleStart; percentReleaseForEachInterval = vestingSchedule .percentReleaseForEachInterval; intervalDays = vestingSchedule.intervalDays; gapDays = vestingSchedule.gapDays; numberOfIntervals = vestingSchedule.numberOfIntervals; releaseMethod = vestingSchedule.releaseMethod; } function vestingGrantFor(address account) external view override returns ( uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive ) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; grantAmount = vestingGrant.grantAmount; isRevocable = vestingGrant.isRevocable; isRevoked = vestingGrant.isRevoked; isActive = vestingGrant.isActive; } function revoked(address account) public view override returns (bool isRevoked) { require(account != address(0), "Vesting: zero account"); isRevoked = _vestingGrants[account].isRevoked; } function releasedAmountFor(address account) public view override returns (uint256 releasedAmount) { require(account != address(0), "Vesting: zero account"); releasedAmount = _released[account]; } function releasableAmountFor(address account) public view override returns (uint256 releasableAmount) { require(account != address(0), "Vesting: zero account"); uint256 startTimestamp = scheduleStartTimestamp; require(startTimestamp > 0, "Vesting: undefined start time"); require(block.timestamp >= startTimestamp, "Vesting: not started"); require(!revoked(account), "Vesting: revoked"); uint256 vestedAmount = vestedAmountFor(account); releasableAmount = vestedAmount.sub(releasedAmountFor(account)); } function vestedAmountFor(address account) public view override returns (uint256 vestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); uint256 startTimestamp = scheduleStartTimestamp; if (startTimestamp == 0) { return 0; } if (block.timestamp < startTimestamp) { return 0; } if (revoked(account)) { return releasedAmountFor(account); } VestingSchedule memory vestingSchedule = _vestingSchedule; vestedAmount = 0; if (vestingSchedule.percentReleaseAtScheduleStart > 0) { vestedAmount = vestingGrant .grantAmount .mul(vestingSchedule.percentReleaseAtScheduleStart) .div(PERCENT_100_WEI); } uint256 cliffEndTimestamp = startTimestamp.add( vestingSchedule.cliffDurationDays.mul(SECONDS_IN_DAY) ); if (block.timestamp < cliffEndTimestamp) { return vestedAmount; } uint256 intervalSeconds = vestingSchedule.intervalDays.mul( SECONDS_IN_DAY ); uint256 gapSeconds = vestingSchedule.gapDays.mul(SECONDS_IN_DAY); uint256 scheduleEndTimestamp = vestingSchedule.numberOfIntervals > 0 ? cliffEndTimestamp .add(intervalSeconds.mul(vestingSchedule.numberOfIntervals)) .add(gapSeconds.mul(vestingSchedule.numberOfIntervals.sub(1))) : cliffEndTimestamp; if (block.timestamp >= scheduleEndTimestamp) { vestedAmount = vestingGrant.grantAmount; return vestedAmount; } // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 intervalNumber = block.timestamp.sub(cliffEndTimestamp).div( intervalSeconds.add(gapSeconds) ); require( intervalNumber < vestingSchedule.numberOfIntervals, "Vesting: unexpected interval number" ); // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 totalPercentage = vestingSchedule .percentReleaseForEachInterval .mul(intervalNumber); if (vestingSchedule.releaseMethod == ReleaseMethod.IntervalEnd) { // solhint-disable-previous-line no-empty-blocks } else if ( vestingSchedule.releaseMethod == ReleaseMethod.LinearlyPerSecond ) { // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply // slither-disable-next-line divide-before-multiply uint256 secondsInInterval = block.timestamp.sub( cliffEndTimestamp.add( intervalSeconds.add(gapSeconds).mul(intervalNumber) ) ); totalPercentage = secondsInInterval >= intervalSeconds ? totalPercentage.add( vestingSchedule.percentReleaseForEachInterval ) : totalPercentage.add( vestingSchedule .percentReleaseForEachInterval .mul(secondsInInterval) .div(intervalSeconds) ); } else { require(false, "Vesting: unexpected release method"); } uint256 maxPercentage = PERCENT_100_WEI.sub( vestingSchedule.percentReleaseAtScheduleStart ); if (totalPercentage > maxPercentage) { totalPercentage = maxPercentage; } vestedAmount = vestedAmount.add( vestingGrant.grantAmount.mul(totalPercentage).div(PERCENT_100_WEI) ); } function unvestedAmountFor(address account) external view override returns (uint256 unvestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); if (revoked(account)) { unvestedAmount = 0; } else { unvestedAmount = vestingGrant.grantAmount.sub( vestedAmountFor(account) ); } } function _addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) private { require(account != address(0), "Vesting: zero account"); require(grantAmount > 0, "Vesting: zero grant amount"); uint256 startTimestamp = scheduleStartTimestamp; require( startTimestamp == 0 || block.timestamp < startTimestamp, "Vesting: already started" ); VestingGrant memory vestingGrant = _vestingGrants[account]; require( allowAccumulate || !vestingGrant.isActive, "Vesting: already added" ); require(!revoked(account), "Vesting: already revoked"); totalGrantAmount = totalGrantAmount.add(grantAmount); require( totalGrantAmount <= IERC20(tokenAddress).balanceOf(address(this)), "Vesting: total grant amount exceed balance" ); if (vestingGrant.isActive) { _vestingGrants[account].grantAmount = vestingGrant.grantAmount.add( grantAmount ); // _vestingGrants[account].isRevocable = isRevocable; } else { _vestingGrants[account] = VestingGrant({ grantAmount: grantAmount, isRevocable: isRevocable, isRevoked: false, isActive: true }); } emit VestingGrantAdded(account, grantAmount, isRevocable); } function _revokeVestingGrant(address account) private { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); require(vestingGrant.isRevocable, "Vesting: not revocable"); require(!revoked(account), "Vesting: already revoked"); uint256 releasedAmount = releasedAmountFor(account); uint256 remainderAmount = vestingGrant.grantAmount.sub(releasedAmount); totalGrantAmount = totalGrantAmount.sub(remainderAmount); _vestingGrants[account].isRevoked = true; emit VestingGrantRevoked( account, remainderAmount, vestingGrant.grantAmount, releasedAmount ); } function _release(address account, uint256 amount) private { require(account != address(0), "Vesting: zero account"); require(amount > 0, "Vesting: zero amount"); _released[account] = _released[account].add(amount); totalReleasedAmount = totalReleasedAmount.add(amount); emit TokensReleased(account, amount); IERC20(tokenAddress).safeTransfer(account, amount); } } // 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: Apache-2.0 // Copyright 2021 Enjinstarter pragma solidity ^0.7.6; /** * @title IVesting * @author Enjinstarter */ interface IVesting { enum ReleaseMethod { IntervalEnd, // 0: at end of each interval LinearlyPerSecond // 1: linearly per second across interval } function addVestingGrant( address account, uint256 grantAmount, bool isRevocable ) external; function revokeVestingGrant(address account) external; function release() external; function transferUnusedTokens() external; function addVestingGrantsBatch( address[] memory accounts, uint256[] memory grantAmounts, bool[] memory isRevocables ) external; function setScheduleStartTimestamp(uint256 scheduleStartTimestamp_) external; function setGovernanceAccount(address account) external; function setVestingAdmin(address account) external; function getVestingSchedule() external view returns ( uint256 cliffDurationDays, uint256 percentReleaseAtGrantStart, uint256 percentReleaseAtIntervalStart, uint256 intervalDays, uint256 gapDays, uint256 numberOfIntervals, ReleaseMethod releaseMethod ); function vestingGrantFor(address account) external view returns ( uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive ); function revoked(address account) external view returns (bool isRevoked); function releasedAmountFor(address account) external view returns (uint256 releasedAmount); function releasableAmountFor(address account) external view returns (uint256 unreleasedAmount); function vestedAmountFor(address account) external view returns (uint256 vestedAmount); function unvestedAmountFor(address account) external view returns (uint256 unvestedAmount); event VestingGrantAdded( address indexed account, uint256 indexed grantAmount, bool isRevocable ); event VestingGrantRevoked( address indexed account, uint256 remainderAmount, uint256 grantAmount, uint256 releasedAmount ); event TokensReleased(address indexed account, uint256 amount); event ScheduleStartTimestampSet( address indexed account, uint256 newScheduleStartTimestamp, uint256 oldScheduleStartTimestamp ); } // 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.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); } } } }
solhint-disable-previous-line no-empty-blocks https:github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply slither-disable-next-line divide-before-multiply
function vestedAmountFor(address account) public view override returns (uint256 vestedAmount) { require(account != address(0), "Vesting: zero account"); VestingGrant memory vestingGrant = _vestingGrants[account]; require(vestingGrant.isActive, "Vesting: inactive"); uint256 startTimestamp = scheduleStartTimestamp; if (startTimestamp == 0) { return 0; } if (block.timestamp < startTimestamp) { return 0; } if (revoked(account)) { return releasedAmountFor(account); } VestingSchedule memory vestingSchedule = _vestingSchedule; vestedAmount = 0; if (vestingSchedule.percentReleaseAtScheduleStart > 0) { vestedAmount = vestingGrant .grantAmount .mul(vestingSchedule.percentReleaseAtScheduleStart) .div(PERCENT_100_WEI); } uint256 cliffEndTimestamp = startTimestamp.add( vestingSchedule.cliffDurationDays.mul(SECONDS_IN_DAY) ); if (block.timestamp < cliffEndTimestamp) { return vestedAmount; } uint256 intervalSeconds = vestingSchedule.intervalDays.mul( SECONDS_IN_DAY ); uint256 gapSeconds = vestingSchedule.gapDays.mul(SECONDS_IN_DAY); uint256 scheduleEndTimestamp = vestingSchedule.numberOfIntervals > 0 ? cliffEndTimestamp .add(intervalSeconds.mul(vestingSchedule.numberOfIntervals)) .add(gapSeconds.mul(vestingSchedule.numberOfIntervals.sub(1))) : cliffEndTimestamp; if (block.timestamp >= scheduleEndTimestamp) { vestedAmount = vestingGrant.grantAmount; return vestedAmount; } intervalSeconds.add(gapSeconds) ); require( intervalNumber < vestingSchedule.numberOfIntervals, "Vesting: unexpected interval number" ); .percentReleaseForEachInterval .mul(intervalNumber); if (vestingSchedule.releaseMethod == ReleaseMethod.IntervalEnd) { } else if ( vestingSchedule.releaseMethod == ReleaseMethod.LinearlyPerSecond ) { uint256 secondsInInterval = block.timestamp.sub( cliffEndTimestamp.add( intervalSeconds.add(gapSeconds).mul(intervalNumber) ) ); totalPercentage = secondsInInterval >= intervalSeconds ? totalPercentage.add( vestingSchedule.percentReleaseForEachInterval ) : totalPercentage.add( vestingSchedule .percentReleaseForEachInterval .mul(secondsInInterval) .div(intervalSeconds) ); require(false, "Vesting: unexpected release method"); } uint256 maxPercentage = PERCENT_100_WEI.sub( vestingSchedule.percentReleaseAtScheduleStart ); if (totalPercentage > maxPercentage) { totalPercentage = maxPercentage; } vestedAmount = vestedAmount.add( vestingGrant.grantAmount.mul(totalPercentage).div(PERCENT_100_WEI) ); }
5,875,414
[ 1, 18281, 11317, 17, 8394, 17, 11515, 17, 1369, 1158, 17, 5531, 17, 7996, 2333, 30, 6662, 18, 832, 19, 71, 1176, 88, 335, 19, 2069, 2927, 19, 13044, 19, 12594, 17, 18905, 2892, 831, 17, 5771, 17, 7027, 1283, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 12326, 17, 5771, 17, 7027, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 331, 3149, 6275, 1290, 12, 2867, 2236, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 331, 3149, 6275, 13, 203, 565, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 3631, 315, 58, 10100, 30, 3634, 2236, 8863, 203, 203, 3639, 776, 10100, 9021, 3778, 331, 10100, 9021, 273, 389, 90, 10100, 29598, 63, 4631, 15533, 203, 3639, 2583, 12, 90, 10100, 9021, 18, 291, 3896, 16, 315, 58, 10100, 30, 16838, 8863, 203, 203, 3639, 2254, 5034, 787, 4921, 273, 4788, 1685, 4921, 31, 203, 203, 3639, 309, 261, 1937, 4921, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 2629, 18, 5508, 411, 787, 4921, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 9083, 14276, 12, 4631, 3719, 288, 203, 5411, 327, 15976, 6275, 1290, 12, 4631, 1769, 203, 3639, 289, 203, 203, 3639, 776, 10100, 6061, 3778, 331, 10100, 6061, 273, 389, 90, 10100, 6061, 31, 203, 203, 3639, 331, 3149, 6275, 273, 374, 31, 203, 203, 3639, 309, 261, 90, 10100, 6061, 18, 8849, 7391, 861, 6061, 1685, 405, 374, 13, 288, 203, 5411, 331, 3149, 6275, 273, 331, 10100, 9021, 203, 7734, 263, 16243, 6275, 203, 7734, 263, 16411, 12, 90, 10100, 6061, 18, 8849, 7391, 861, 6061, 1685, 13, 203, 7734, 263, 2892, 12, 3194, 19666, 67, 6625, 67, 6950, 45, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 927, 3048, 2 ]
// File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } //SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; contract BEMETA_WomansBigEyes is ERC721, ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI = "https://ipfs.io/ipfs/QmTL7ZL39w6cP8zu1cMYxTfJFDXwg4WdQtEj4Yd1YWVBBe"; string public baseExtension = ".json"; uint256 public bonusPrice = 0.025 ether; uint256 public holdersPrice = 0.035 ether; uint256 public weekendPrice = 0.04 ether; uint256 public regularPrice = 0.05 ether; uint256 public maxSupply = 10000; uint256 public maxMintAmount = 5; uint256 public bonusSaleDate = 1650643200; // 22 April 2022 16:00:00 GMT uint256 public regularSaleDate = 1650902400; // 25 April 2022 16:00:00 GMT bool public paused = false; address public bemmhAddress = 0x2D78c5aC66eCBcaF81aD13060B53a399Bc78D6aa; address public pdartAddress = 0xd287623e852d010DD6df714D90bB4f53103355bB; address public bemftAddress = 0x5dF17fAaA379058B2f4dCa0a3067531785f26d22; mapping(address => uint8) private wl_mint_amount; mapping(address => uint256) private addressMintedBalance; constructor() ERC721("WomansBigEyes", "WBE") {} function _baseURI() internal view virtual override returns (string memory) {return baseURI;} function holdersCost() public view returns (uint256) {if (regularSaleDate < block.timestamp) {return holdersPrice;} else {return bonusPrice;}} function regularCost() public view returns (uint256) {if (regularSaleDate < block.timestamp) {return regularPrice;} else {return weekendPrice;}} function stageOfMinting() public view returns (uint256) // 1 is Bonus Sales period, 2 is Regular Sales {if (regularSaleDate < block.timestamp) {return 2;} else {return 1;}} function numAvailableToMint(address addr) external view returns (uint8) {return wl_mint_amount[addr];} function mint(uint256 _mintAmount) public payable { require(!paused, "The contract is paused"); require(bonusSaleDate < block.timestamp, "Minting is not started"); uint256 supply = totalSupply(); require(_mintAmount > 0, "At least 1 NFT must be minted"); require(supply + _mintAmount <= maxSupply, "Max NFT limit exceeded"); if (msg.sender != owner()) { if(stageOfMinting() == 1) { IERC721 bemmh_token = IERC721(bemmhAddress); IERC721 pdart_token = IERC721(pdartAddress); IERC721 bemft_token = IERC721(bemftAddress); uint256 ownerWLCount = wl_mint_amount[msg.sender]; uint256 owned_bemmh_Amount = bemmh_token.balanceOf(msg.sender); uint256 owned_pdart_Amount = pdart_token.balanceOf(msg.sender); uint256 owned_bemft_Amount = bemft_token.balanceOf(msg.sender); if(ownerWLCount + owned_bemmh_Amount + owned_pdart_Amount + owned_bemft_Amount >= 1) { uint256 owned_nfts_count = 0; if(owned_bemmh_Amount + owned_pdart_Amount + owned_bemft_Amount > 0) { owned_nfts_count = 20;} //BEMETA NFTs holders - 20 bonus mint per holder on bonus weekend uint256 allowWLmintamount = ownerWLCount + owned_nfts_count; uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded"); require(msg.value >= bonusPrice * _mintAmount, "Insufficient funds"); if(ownerMintedCount + _mintAmount <= allowWLmintamount) { require(msg.value < weekendPrice * _mintAmount, "Insufficient funds"); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i);} } else { require(ownerMintedCount == allowWLmintamount, "Max bonus mint amount per session not exceeded"); require(ownerMintedCount + _mintAmount > allowWLmintamount, "Max bonus mint amount per session not exceeded"); require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded"); require(msg.value >= weekendPrice * _mintAmount, "First mint at special price, please"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i);} } } else { require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded"); require(msg.value >= weekendPrice * _mintAmount, "Insufficient funds"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i);} } } else { IERC721 bemmh_token = IERC721(bemmhAddress); IERC721 pdart_token = IERC721(pdartAddress); IERC721 bemft_token = IERC721(bemftAddress); uint256 owned_bemmh_Amount = bemmh_token.balanceOf(msg.sender); uint256 owned_pdart_Amount = pdart_token.balanceOf(msg.sender); uint256 owned_bemft_Amount = bemft_token.balanceOf(msg.sender); if(owned_bemmh_Amount + owned_pdart_Amount + owned_bemft_Amount >= 1) //BEMETA NFTs holders - all time mint with special price for holder { require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded"); require(msg.value >= holdersPrice * _mintAmount, "Insufficient funds"); require(msg.value < regularPrice * _mintAmount, "First mint at special price, please"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i);} } else { require(_mintAmount <= maxMintAmount, "Max mint amount per session exceeded"); require(msg.value >= regularPrice * _mintAmount, "Insufficient funds"); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i);} } } } else { for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } } function alreadyMintedBonus() public view returns (uint256) {uint256 aCount = addressMintedBalance[msg.sender];return (aCount);} function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {super._beforeTokenTransfer(from, to, tokenId);} function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {return super.supportsInterface(interfaceId);} function walletOfOwner(address owner) public view returns (uint256[] memory) {uint256 ownerTokenCount = balanceOf(owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(owner, i);} return tokenIds;} function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : "";} function info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { return (stageOfMinting(), holdersCost(), regularCost(), bonusSaleDate, regularSaleDate, bonusPrice, weekendPrice, holdersPrice, regularPrice);} //only owner function whitelistUsers(address[] calldata addresses, uint8 numAllowedToMint) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) {wl_mint_amount[addresses[i]] = numAllowedToMint;} } function setBonusPrice(uint256 _newBonusPrice) public onlyOwner {bonusPrice = _newBonusPrice;} function setWeekendPrice(uint256 _newWeekendPrice) public onlyOwner {weekendPrice = _newWeekendPrice;} function setHoldersPrice(uint256 _newHoldersPrice) public onlyOwner {holdersPrice = _newHoldersPrice;} function setRegularPrice(uint256 _newRegularPrice) public onlyOwner {regularPrice = _newRegularPrice;} function setBonusSaleDate(uint256 _newBonusSaleDate) public onlyOwner {bonusSaleDate = _newBonusSaleDate;} function setRegularSaleDate(uint256 _newRegularSaleDate) public onlyOwner {regularSaleDate = _newRegularSaleDate;} function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {maxMintAmount = _newmaxMintAmount;} function setBaseURI(string memory _newBaseURI) public onlyOwner {baseURI = _newBaseURI;} function setBaseExtension(string memory _newBaseExtension) public onlyOwner {baseExtension = _newBaseExtension;} function setMaxSupply(uint256 _newMaxSupply) public onlyOwner {maxSupply = _newMaxSupply;} function pause(bool _state) public onlyOwner {paused = _state;} function withdraw() public payable onlyOwner {(bool wo, ) = payable(0x984B4418ad10D5844e8927C8197540514033FfF7).call{value: address(this).balance * 50 / 100}(""); require(wo); (bool wt, ) = payable(0xFAf57c09291C289583216A02864a9C291e48E052).call{value: address(this).balance * 50 / 100}(""); require(wt); (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os);} }
25 April 2022 16:00:00 GMT
uint256 public regularSaleDate = 1650902400;
10,414,446
[ 1, 2947, 432, 683, 330, 26599, 22, 2872, 30, 713, 30, 713, 21706, 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, 225, 2254, 5034, 1071, 6736, 30746, 1626, 273, 2872, 5995, 3103, 16010, 31, 1377, 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 ]
//Address: 0xeDeF91088dB5Abbe9942621b202665B09AEB4C6F //Contract name: UpdateConvRate //Balance: 0 Ether //Verification Date: 2/21/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; interface ERC20 { function transferFrom(address _from, address _to, uint _value) public returns (bool success); } interface TokenConfigInterface { function admin() public returns(address); function claimAdmin() public; function transferAdminQuickly(address newAdmin) public; // conversion rate function setTokenControlInfo( address token, uint minimalRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance ) public; } contract UpdateConvRate { TokenConfigInterface public conversionRate; // address public ETH = 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; ERC20 public ENG = ERC20(0xf0Ee6b27b759C9893Ce4f094b49ad28fd15A23e4); ERC20 public SALT = ERC20(0x4156D3342D5c385a87D264F90653733592000581); ERC20 public APPC = ERC20(0x1a7a8BD9106F2B8D977E08582DC7d24c723ab0DB); ERC20 public RDN = ERC20(0x255Aa6DF07540Cb5d3d297f0D0D4D84cb52bc8e6); ERC20 public OMG = ERC20(0xd26114cd6EE289AccF82350c8d8487fedB8A0C07); ERC20 public KNC = ERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200); ERC20 public EOS = ERC20(0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0); ERC20 public SNT = ERC20(0x744d70FDBE2Ba4CF95131626614a1763DF805B9E); ERC20 public ELF = ERC20(0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e); ERC20 public POWR = ERC20(0x595832F8FC6BF59c85C527fEC3740A1b7a361269); ERC20 public MANA = ERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942); ERC20 public BAT = ERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF); ERC20 public REQ = ERC20(0x8f8221aFbB33998d8584A2B05749bA73c37a938a); ERC20 public GTO = ERC20(0xC5bBaE50781Be1669306b9e001EFF57a2957b09d); function UpdateConvRate (TokenConfigInterface _conversionRate) public { conversionRate = _conversionRate; } function setTokensControlInfo() public { address orgAdmin = conversionRate.admin(); conversionRate.claimAdmin(); conversionRate.setTokenControlInfo( KNC, 1000000000000000, 3209682992192817725440, 5685953420669578379264 ); conversionRate.setTokenControlInfo( OMG, 1000000000000000, 401531338213762269184, 711312765645680017408 ); conversionRate.setTokenControlInfo( EOS, 1000000000000000, 857086802686433558528, 1518329270959017033728 ); conversionRate.setTokenControlInfo( SNT, 10000000000000000, 39473220400186602291200, 51279660621882430849024 ); conversionRate.setTokenControlInfo( GTO, 10, 1298406206, 1298406206); conversionRate.setTokenControlInfo( REQ, 1000000000000000, 26380249265656293228544, 34270581821014091497472); conversionRate.setTokenControlInfo( BAT, 1000000000000000, 13630787405152438452224, 13630787405152438452224); conversionRate.setTokenControlInfo( MANA, 1000000000000000, 46922655822319550726144, 46922655822319550726144); conversionRate.setTokenControlInfo( POWR, 1000, 7698525732, 7698525732); conversionRate.setTokenControlInfo( ELF, 1000000000000000, 5135835425728323649536, 6671963801563665793024); conversionRate.setTokenControlInfo( APPC, 1000000000000000, 9671281647528360017920, 12563961988304091480064); conversionRate.setTokenControlInfo( ENG, 10000, 277385502667, 360351506515); conversionRate.setTokenControlInfo( RDN, 1000000000000000 , 2164249905248327172096, 2811577051908102684672); conversionRate.setTokenControlInfo( SALT, 10000, 121452449847, 121452449847); conversionRate.transferAdminQuickly(orgAdmin); require(orgAdmin == conversionRate.admin()); } }
address public ETH = 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
contract UpdateConvRate { TokenConfigInterface public conversionRate; ERC20 public ENG = ERC20(0xf0Ee6b27b759C9893Ce4f094b49ad28fd15A23e4); ERC20 public SALT = ERC20(0x4156D3342D5c385a87D264F90653733592000581); ERC20 public APPC = ERC20(0x1a7a8BD9106F2B8D977E08582DC7d24c723ab0DB); ERC20 public RDN = ERC20(0x255Aa6DF07540Cb5d3d297f0D0D4D84cb52bc8e6); ERC20 public OMG = ERC20(0xd26114cd6EE289AccF82350c8d8487fedB8A0C07); ERC20 public KNC = ERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200); ERC20 public EOS = ERC20(0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0); ERC20 public SNT = ERC20(0x744d70FDBE2Ba4CF95131626614a1763DF805B9E); ERC20 public ELF = ERC20(0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e); ERC20 public POWR = ERC20(0x595832F8FC6BF59c85C527fEC3740A1b7a361269); ERC20 public MANA = ERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942); ERC20 public BAT = ERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF); ERC20 public REQ = ERC20(0x8f8221aFbB33998d8584A2B05749bA73c37a938a); ERC20 public GTO = ERC20(0xC5bBaE50781Be1669306b9e001EFF57a2957b09d); function UpdateConvRate (TokenConfigInterface _conversionRate) public { conversionRate = _conversionRate; } function setTokensControlInfo() public { address orgAdmin = conversionRate.admin(); conversionRate.claimAdmin(); conversionRate.setTokenControlInfo( KNC, 1000000000000000, 3209682992192817725440, 5685953420669578379264 ); conversionRate.setTokenControlInfo( OMG, 1000000000000000, 401531338213762269184, 711312765645680017408 ); conversionRate.setTokenControlInfo( EOS, 1000000000000000, 857086802686433558528, 1518329270959017033728 ); conversionRate.setTokenControlInfo( SNT, 10000000000000000, 39473220400186602291200, 51279660621882430849024 ); conversionRate.setTokenControlInfo( GTO, 10, 1298406206, 1298406206); conversionRate.setTokenControlInfo( REQ, 1000000000000000, 26380249265656293228544, 34270581821014091497472); conversionRate.setTokenControlInfo( BAT, 1000000000000000, 13630787405152438452224, 13630787405152438452224); conversionRate.setTokenControlInfo( MANA, 1000000000000000, 46922655822319550726144, 46922655822319550726144); conversionRate.setTokenControlInfo( POWR, 1000, 7698525732, 7698525732); conversionRate.setTokenControlInfo( ELF, 1000000000000000, 5135835425728323649536, 6671963801563665793024); conversionRate.setTokenControlInfo( APPC, 1000000000000000, 9671281647528360017920, 12563961988304091480064); conversionRate.setTokenControlInfo( ENG, 10000, 277385502667, 360351506515); conversionRate.setTokenControlInfo( RDN, 1000000000000000 , 2164249905248327172096, 2811577051908102684672); conversionRate.setTokenControlInfo( SALT, 10000, 121452449847, 121452449847); conversionRate.transferAdminQuickly(orgAdmin); require(orgAdmin == conversionRate.admin()); } }
15,811,722
[ 1, 2867, 1071, 512, 2455, 273, 374, 92, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 1340, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 16351, 2315, 17467, 4727, 288, 203, 565, 3155, 809, 1358, 1071, 4105, 4727, 31, 203, 203, 565, 4232, 39, 3462, 1071, 17979, 273, 4232, 39, 3462, 12, 20, 5841, 20, 41, 73, 26, 70, 5324, 70, 5877, 29, 39, 29, 6675, 23, 39, 73, 24, 74, 5908, 24, 70, 7616, 361, 6030, 8313, 3600, 37, 4366, 73, 24, 1769, 203, 565, 4232, 39, 3462, 1071, 348, 18255, 273, 4232, 39, 3462, 12, 20, 92, 24, 28946, 40, 3707, 9452, 40, 25, 71, 23, 7140, 69, 11035, 40, 23728, 42, 29, 7677, 25, 6418, 3707, 6162, 17172, 8204, 21, 1769, 203, 565, 4232, 39, 3462, 1071, 14410, 3513, 273, 4232, 39, 3462, 12, 20, 92, 21, 69, 27, 69, 28, 18096, 29, 22135, 42, 22, 38, 28, 40, 29, 4700, 41, 6840, 8204, 22, 5528, 27, 72, 3247, 71, 27, 4366, 378, 20, 2290, 1769, 203, 565, 4232, 39, 3462, 1071, 534, 8609, 273, 4232, 39, 3462, 12, 20, 92, 10395, 37, 69, 26, 4577, 20, 5877, 7132, 15237, 25, 72, 23, 72, 5540, 27, 74, 20, 40, 20, 40, 24, 40, 5193, 7358, 9401, 13459, 28, 73, 26, 1769, 203, 565, 4232, 39, 3462, 1071, 28839, 43, 273, 4232, 39, 3462, 12, 20, 7669, 5558, 22214, 4315, 26, 9383, 6030, 29, 8973, 42, 28, 4366, 3361, 71, 28, 72, 5193, 11035, 31835, 38, 28, 37, 20, 39, 8642, 1769, 203, 565, 4232, 39, 3462, 1071, 1475, 10346, 273, 4232, 39, 3462, 12, 20, 92, 449, 29, 5608, 40, 25, 39, 22, 73, 5540, 6030, 2 ]
./partial_match/5/0x97cf1AF3E72704ea490c640480df6D7655BF8601/sources/logic.sol
20*0.98 for referal20*0.02 for jackpot jackpot= jackpot+ (20-reward) ;
function rewardDistribution_v1(address _user)public{ uint reward = 20; User[_user].pendingRewards =User[_user].pendingRewards+reward; }
16,868,840
[ 1, 6976, 18, 10689, 364, 8884, 287, 6976, 18, 3103, 364, 525, 484, 13130, 525, 484, 13130, 33, 525, 484, 13130, 15, 261, 3462, 17, 266, 2913, 13, 274, 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, 445, 19890, 9003, 67, 90, 21, 12, 2867, 389, 1355, 13, 482, 95, 203, 540, 203, 3639, 2254, 19890, 273, 4200, 31, 203, 3639, 2177, 63, 67, 1355, 8009, 9561, 17631, 14727, 273, 1299, 63, 67, 1355, 8009, 9561, 17631, 14727, 15, 266, 2913, 31, 203, 203, 3639, 203, 565, 289, 203, 377, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8536850750956c2FEebeCAB786d82271a5467687/sources/AcceptModifications.sol
Verifier authorizes withdrawal.
function acceptWithdrawal( uint256 ownerKey, uint256 assetId, uint256 quantizedAmount ) internal virtual override { allowWithdrawal(ownerKey, assetId, quantizedAmount); }
3,944,739
[ 1, 17758, 2869, 3128, 598, 9446, 287, 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, 2791, 1190, 9446, 287, 12, 203, 3639, 2254, 5034, 3410, 653, 16, 203, 3639, 2254, 5034, 3310, 548, 16, 203, 3639, 2254, 5034, 10251, 1235, 6275, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 1699, 1190, 9446, 287, 12, 8443, 653, 16, 3310, 548, 16, 10251, 1235, 6275, 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 ]
./full_match/56/0x880688e61Dd56e2cEA8D7d0413aef823F282a82a/sources/contracts/Config.sol
某个标签对应的地址,例如shop=》address,表示商店的合约地址
mapping(string => address) private labelAddressMap;
3,233,980
[ 1, 167, 258, 243, 165, 121, 108, 167, 259, 234, 168, 260, 127, 166, 112, 122, 166, 123, 247, 168, 253, 231, 166, 255, 113, 166, 256, 227, 176, 125, 239, 165, 127, 238, 166, 104, 229, 5020, 33, 164, 227, 238, 2867, 176, 125, 239, 169, 99, 106, 168, 102, 123, 166, 248, 233, 166, 123, 250, 168, 253, 231, 166, 243, 235, 168, 123, 104, 166, 255, 113, 166, 256, 227, 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, 2874, 12, 1080, 516, 1758, 13, 3238, 1433, 1887, 863, 31, 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 ]
./full_match/1/0x5069FBfFB1F65e6C3D9EfE7C70c4c0d13524e960/sources/contracts/Daydreamers.sol
* @notice Ensure function cannot be called outside of a given mint phase @param _mintPhase Correct mint phase for function to execute/
modifier inMintPhase(MintPhase _mintPhase) { if (mintPhase != _mintPhase) { revert IncorrectMintPhase(); } _; }
3,199,460
[ 1, 12512, 445, 2780, 506, 2566, 8220, 434, 279, 864, 312, 474, 6855, 225, 389, 81, 474, 11406, 30626, 312, 474, 6855, 364, 445, 358, 1836, 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 ]
[ 1, 1, 1, 1, 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 ]
[ 1, 565, 9606, 316, 49, 474, 11406, 12, 49, 474, 11406, 389, 81, 474, 11406, 13, 288, 203, 3639, 309, 261, 81, 474, 11406, 480, 389, 81, 474, 11406, 13, 288, 203, 5411, 15226, 657, 6746, 49, 474, 11406, 5621, 203, 3639, 289, 203, 3639, 389, 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 ]
// SPDX-License-Identifier: MIT /** * PowerBull (https://powerbull.net) * @author PowerBull <[email protected]> */ pragma solidity ^0.8.0; pragma abicoder v2; import "./libs/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IHoldlersRewardComputer.sol"; import "./StructsDef.sol"; import "./Commons.sol"; //import "./interfaces/ISwapEngine.sol"; import "./libs/@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import "./libs/@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "./libs/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "hardhat/console.sol"; contract PBull is Context, Ownable, ERC20, Commons { event Receive(address _sender, uint256 _amount); using SafeMath for uint256; string private constant _tokenName = "Luckie Jodjie 4"; string private constant _tokenSymbol = "LLJ4"; uint8 private constant _tokenDecimals = 18; uint256 private constant _tokenSupply = 26_000_000 * (10 ** _tokenDecimals); // 25m /////////////////////// This will deposit _initialPercentageOfTokensForRewardPool into the reward pool for the users to split over time ///////////// /////////////////////// Note this is a one time during contract initialization /////////////////////////////////////////////////////// uint256 public constant _initialPercentOfTokensForHoldlersRewardPool = 100; /// 1% of total supply // reward token address rewardTokenAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // wbnb token ERC20 rewardTokenContract = ERC20(rewardTokenAddress); // reward limit before release uint256 public rewardLimitBeforeRelease = 1 * (10 ** rewardTokenContract.decimals()); // tax uint256 public marketingFee = 100; // 100 = 1% uint256 public devFee = 100; // 100 = 1% // set the dev and marketing wallet here, default is deployer address payable devAndMarketingWallet; bool public isAutoLiquidityEnabled = true; bool public isHoldlersRewardEnabled = true; bool public isBuyBackEnabled = true; bool public isSellTaxEnabled = true; bool public isMarketingFeeEnabled = true; bool public isDevFeeEnabled = true; //using basis point, multiple number by 100 uint256 public holdlersRewardFee = 100; // 1% for holdlers reward pool uint256 public autoLiquidityFee = 100; // 1% fee charged on tx for adding liquidity pool uint256 public buyBackFee = 100; // 1% will be used for buyback uint256 public sellTaxFee = 50; // 1% a sell tax fee, which applies to sell only //buyback uint256 public minAmountBeforeSellingTokenForBuyBack = 50_000 * (10 ** _tokenDecimals); uint256 public minAmountBeforeSellingETHForBuyBack = 1 ether; uint256 public buyBackETHAmountSplitDivisor = 100; uint256 public buyBackTokenPool; uint256 public buyBackETHPool; uint256 public totalBuyBacksAmountInTokens; uint256 public totalBuyBacksAmountInETH; // funds pool uint256 public autoLiquidityPool; //uint256 public autoBurnPool; uint256 public liquidityProvidersIncentivePool; //////////////////////////////// START REWARD POOL /////////////////////////// // token pool to sell or credit to the main pools uint256 public pendingRewardTokenPool; uint256 public holdlersRewardMainPool; // reward pool reserve used in replenishing the main pool any time someone withdraw else // the others holdlers will see a reduction in rewards uint256 public holdlersRewardReservedPool; ////// percentage of reward we should allocate to reserve pool uint256 public percentageShareOfHoldlersRewardsForReservedPool = 3000; /// 30% in basis point system // The minimum amount required to keep in the holdlersRewardsReservePool // this means if the reserve pool goes less than minPercentOfReserveRewardToMainRewardPool of the main pool, use // next collected fee for rewards into the reserve pool till its greater than minPercentOfReserveRewardToMainRewardPool uint256 public minPercentageOfholdlersRewardReservedPoolToMainPool = 3000; /// 30% in basis point system ///////////////////////////////// END REWARD POOL //////////////////////////// // liquidity owner address public autoLiquidityOwner; //minimum amount before adding auto liquidity uint256 public minAmountBeforeAutoLiquidity = 60_000 * (10 ** _tokenDecimals); // minimum amount before auto burn uint256 public minAmountBeforeAutoBurn = 500_000 * (10 ** _tokenDecimals); bytes32 public txTypeForMaxTxAmountLimit = keccak256(abi.encodePacked("TX_SELL")); ///////////////////// START MAPS /////////////////////// //accounts excluded from fees mapping(address => bool) public excludedFromFees; mapping(address => bool) public excludedFromRewards; mapping(address => bool) public excludedFromPausable; // permit nonces mapping(address => uint) public nonces; //acounts deposit info mapping keeping all user info // address => initial Deposit timestamp mapping(address => StructsDef.HoldlerInfo) private holdlersInfo; ////////////////// END MAPS //////////////// uint256 public totalRewardsTaken; bool isSwapAndLiquidifyLocked; // extending erc20 to support permit bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // timestamp the contract was deployed uint256 public immutable deploymentTimestamp; // isPaused bool public isPaused; // if contract is paused // total token holders uint256 public totalTokenHolders; // external contracts IHoldlersRewardComputer public holdlersRewardComputer; // ISwapEngine public swapEngine; //ITeams public teamsContract; uint256 public totalLiquidityAdded; //////// WETHER the token is initialized or not ///////////// bool public initialized; // token contract address public immutable _tokenAddress; IUniswapV2Router02 public uniswapRouter; address public uniswapPair; IUniswapV2Pair public uniswapPairContract; address WETH; bytes32 public TX_TRANSFER = keccak256(abi.encodePacked("TX_TRANSFER")); bytes32 public TX_SELL = keccak256(abi.encodePacked("TX_SELL")); bytes32 public TX_BUY = keccak256(abi.encodePacked("TX_BUY")); bytes32 public TX_ADD_LIQUIDITY = keccak256(abi.encodePacked("TX_ADD_LIQUIDITY")); bytes32 public TX_REMOVE_LIQUIDITY = keccak256(abi.encodePacked("TX_REMOVE_LIQUIDIY")); address public burnAddress = 0x000000000000000000000000000000000000dEaD; ///////// Dev and marketing wallet ///////////////// uint256 public devAndMarketingFundPool; // constructor constructor() ERC20 (_tokenName,_tokenSymbol, _tokenDecimals) { // initialize token address _tokenAddress = address(this); // mint _mint(_msgSender(), _tokenSupply); if(devAndMarketingWallet == address(0)) { // set dev and marketing wallet to deployer devAndMarketingWallet = payable(_msgSender()); } //excludes for excludedFromFees[address(this)] = true; excludedFromRewards[address(this)] = true; excludedFromPausable[address(this)] = true; //excludes for owner excludedFromFees[_msgSender()] = true; excludedFromPausable[_msgSender()] = true; excludedFromPausable[_msgSender()] = true; // set auto liquidity owner autoLiquidityOwner = _msgSender(); // set the deploymenet time deploymentTimestamp = block.timestamp; // permit domain separator DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name())), keccak256(bytes('1')), getChainId(), address(this) ) ); } //end constructor /** * initialize the project * @param _uniswapRouter the uniswap router * @param _holdlersRewardComputer the holdlers reward computer */ function _initializeContract ( address _uniswapRouter, address _holdlersRewardComputer ) public onlyOwner { require(!initialized, "PBULL: ALREADY_INITIALIZED"); require(_holdlersRewardComputer != address(0), "PBULL: INVALID_HOLDLERS_REWARD_COMPUTER_CONTRACT"); // this will update the uniswap router again setUniswapRouter(_uniswapRouter); holdlersRewardComputer = IHoldlersRewardComputer(_holdlersRewardComputer); if(rewardTokenAddress == address(this)){ // lets deposit holdlers reward pool initial funds processHoldlersRewardPoolInitialFunds(); } initialized = true; } //end intialize /** * @dev processRewardPool Initial Funds */ function processHoldlersRewardPoolInitialFunds() private { require(!initialized, "PBULL: ALREADY_INITIALIZED"); // if no tokens were assign to the rewards dont process if(_initialPercentOfTokensForHoldlersRewardPool == 0){ return; } //let get the rewardPool initial funds uint256 rewardPoolInitialFunds = percentToAmount(_initialPercentOfTokensForHoldlersRewardPool, totalSupply()); //first of all lets move funds to the contract internalTransfer(_msgSender(), _tokenAddress, rewardPoolInitialFunds,"REWARD_POOL_INITIAL_FUNDS_TRANSFER_ERROR", true); uint256 rewardsPoolsFundSplit = rewardPoolInitialFunds.sub(2); // lets split them 50% 50% into the rewardmainPool and rewards Reserved pool holdlersRewardMainPool = holdlersRewardMainPool.add(rewardsPoolsFundSplit); // lets put 50% into the reserve pool holdlersRewardReservedPool = holdlersRewardReservedPool.add(rewardsPoolsFundSplit); } //end function receive () external payable { emit Receive(_msgSender(), msg.value ); } fallback () external payable {} /** * lock swap or add liquidity activity */ modifier lockSwapAndLiquidify { isSwapAndLiquidifyLocked = true; _; isSwapAndLiquidifyLocked = false; } /** * get chain Id */ function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev erc20 permit */ function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'PBULL: PERMIT_EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'PBULL: PERMIT_INVALID_SIGNATURE'); _approve(owner, spender, value); } /** * realBalanceOf - get account real balance */ function realBalanceOf(address _account) public view returns(uint256) { return super.balanceOf(_account); } /** * override balanceOf - This now returns user balance + reward **/ function balanceOf(address _account) override public view returns(uint256) { uint256 accountBalance = super.balanceOf(_account); if(!( rewardTokenAddress == address(0) || rewardTokenAddress == address(this) )) { return accountBalance; } if(accountBalance <= 0){ accountBalance = 0; } uint256 reward = getReward(_account); if(reward <= 0){ return accountBalance; } return (accountBalance.add(reward)); } //end fun ////////////////////////// HOLDERS REWARD COMPUTER FUNCTIONS /////////////////// /** * get an account reward * @param _account the account to get the reward info */ function getReward(address _account) public view returns(uint256) { if(!isHoldlersRewardEnabled || excludedFromRewards[_account]) { return 0; } uint256 reward = holdlersRewardComputer.getReward(_account); if(reward <= 0){ return 0; } return reward; }//end get reward /** * @dev the delay in seconds before a holdlers starts seeing rewards after initial deposit * @return time in seconds */ function rewardStartDelay() public view returns(uint256) { return holdlersRewardComputer.rewardStartDelay(); } /** * @dev set the number of delay in time before a reward starts showing up * @param _delayInSeconds the delay in seconds */ function setRewardStartDelay(uint256 _delayInSeconds) public onlyOwner { holdlersRewardComputer.setRewardStartDelay(_delayInSeconds); } /** * @dev the minimum expected holdl period * @return time in seconds */ function minExpectedHoldlPeriod() public view returns (uint256) { return holdlersRewardComputer.minExpectedHoldlPeriod(); } /** * @dev set the minimum expected holdl period * @param _timeInSeconds time in seconds */ function setMinExpectedHoldlPeriod(uint256 _timeInSeconds) public onlyOwner { holdlersRewardComputer.setMinExpectedHoldlPeriod(_timeInSeconds); } /** * enableMarketingFee */ function enableMarketingFee(bool _option) public onlyOwner { isMarketingFeeEnabled = _option; } /** * setMarketingWallet */ function setMarketingFee(uint256 _value) public onlyOwner { marketingFee = _value; } /** * setDevWallet */ function setDevFee(uint256 _value) public onlyOwner { devFee = _value; } /** * enableMarketingFee */ function enableDevFee(bool _option) public onlyOwner { isDevFeeEnabled = _option; } /** * setMarketingWallet */ function setDevAndMarketingWallet(address payable _wallet) public onlyOwner { devAndMarketingWallet = _wallet; } ////////////////////////// END HOLDERS REWARD COMPUTER FUNCTIONS /////////////////// /** * @dev get initial deposit time * @param _account the account to get the info * @return account tx info */ function getHoldlerInfo(address _account) public view returns (StructsDef.HoldlerInfo memory) { return holdlersInfo[_account]; } //////////////////////// START OPTION SETTER ///////////////// /** * @dev set auto liquidity owner address * @param _account the EOS address for system liquidity */ function setAutoLiquidityOwner(address _account) public onlyOwner { autoLiquidityOwner = _account; } /** * @dev enable or disable auto buyback * @param _option true to enable, false to disable */ function enableBuyBack(bool _option) public onlyOwner { isBuyBackEnabled = _option; } /** * @dev enable or disable auto liquidity * @param _option true to enable, false to disable */ function enableAutoLiquidity(bool _option) public onlyOwner { isAutoLiquidityEnabled = _option; } /** * @dev enable or disable holdlers reward * @param _option true to enable, false to disable */ function enableHoldlersReward(bool _option) public onlyOwner { isHoldlersRewardEnabled = _option; } /** * @dev enable or disable sell Tax * @param _option true to enable, false to disable */ function enableSellTax(bool _option) public onlyOwner { isSellTaxEnabled = _option; } /** * @dev enable or disable all fees * @param _option true to enable, false to disable */ function enableAllFees(bool _option) public onlyOwner { isBuyBackEnabled = _option; isAutoLiquidityEnabled = _option; isHoldlersRewardEnabled = _option; isSellTaxEnabled = _option; isDevFeeEnabled = _option; isMarketingFeeEnabled = _option; } //////////////////// END OPTION SETTER ////////// ///////////////////// START SETTER /////////////// /** * @dev set the auto buyback fee * @param _valueBps the fee value in basis point system */ function setBuyBackFee(uint256 _valueBps) public onlyOwner { buyBackFee = _valueBps; } /** * @dev set holdlers reward fee * @param _valueBps the fee value in basis point system */ function setHoldlersRewardFee(uint256 _valueBps) public onlyOwner { holdlersRewardFee = _valueBps; } /** * @dev auto liquidity fee * @param _valueBps the fee value in basis point system */ function setAutoLiquidityFee(uint256 _valueBps) public onlyOwner { autoLiquidityFee = _valueBps; } /** * @dev set Sell Tax Fee * @param _valueBps the fee value in basis point system */ function setSellTaxFee(uint256 _valueBps) public onlyOwner { sellTaxFee = _valueBps; } //////////////////////////// END SETTER ///////////////// /** * @dev get total fee * @return the total fee in uint256 number */ function getTotalFee() public view returns(uint256){ uint256 fee = 0; if(isBuyBackEnabled){ fee += buyBackFee; } if(isAutoLiquidityEnabled){ fee += autoLiquidityFee; } if(isHoldlersRewardEnabled){ fee += holdlersRewardFee; } if(isSellTaxEnabled) { fee += sellTaxFee; } if(isDevFeeEnabled) { fee += devFee; } if(isMarketingFeeEnabled) { fee += marketingFee; } return fee; } //end function /** * @dev set holders reward computer contract called HoldlEffect * @param _contractAddress the contract address */ function setHoldlersRewardComputer(address _contractAddress) public onlyOwner { require(_contractAddress != address(0),"PBULL: SET_HOLDLERS_REWARD_COMPUTER_INVALID_ADDRESS"); holdlersRewardComputer = IHoldlersRewardComputer(_contractAddress); } /** * @dev set uniswap router address * @param _uniswapRouter uniswap router contract address */ function setUniswapRouter(address _uniswapRouter) public onlyOwner { require(_uniswapRouter != address(0), "PBULL#SWAP_ENGINE: ZERO_ADDRESS"); if(_uniswapRouter == address(uniswapRouter)){ return; } address _oldRouter = address(uniswapRouter); uniswapRouter = IUniswapV2Router02(_uniswapRouter); IUniswapV2Factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory()); WETH = uniswapRouter.WETH(); uniswapPair = uniswapFactory.getPair( address(this), WETH); if(uniswapPair == address(0)) { // Create a uniswap pair for this new token uniswapPair = uniswapFactory.createPair( address(this), WETH); } uniswapPairContract = IUniswapV2Pair(uniswapPair); // lets disable rewards for uniswap pair and router excludedFromRewards[_uniswapRouter] = true; excludedFromRewards[uniswapPair] = true; } ////////////////// START EXCLUDES //////////////// /** * @dev exclude or include an account from paying fees * @param _option true to exclude, false to include */ function excludeFromFees(address _account, bool _option) public onlyOwner { excludedFromFees[_account] = _option; } /** * @dev exclude or include an account from getting rewards * @param _option true to exclude, false to include */ function excludeFromRewards(address _account, bool _option) public onlyOwner { excludedFromRewards[_account] = _option; } /** * @dev exclude from paused * @param _option true to exclude, false to include */ function excludeFromPausable(address _account, bool _option) public onlyOwner { excludedFromPausable[_account] = _option; } //////////////////// END EXCLUDES /////////////////// /** * @dev minimum amount before adding auto liquidity * @param _amount the amount of tokens before executing auto liquidity */ function setMinAmountBeforeAutoLiquidity(uint256 _amount) public onlyOwner { minAmountBeforeAutoLiquidity = _amount; } /** * @dev set min amount before auto burning * @param _amount the minimum amount when reached we should auto burn */ function setMinAmountBeforeAutoBurn(uint256 _amount) public onlyOwner { minAmountBeforeAutoBurn = _amount; } /** * @dev set min amount before selling tokens for buyback * @param _amount the minimum amount */ function setMinAmountBeforeSellingETHForBuyBack(uint256 _amount) public onlyOwner { minAmountBeforeSellingETHForBuyBack = _amount; } /** * @dev set min amount before selling tokens for buyback * @param _amount the minimum amount */ function setMinAmountBeforeSellingTokenForBuyBack(uint256 _amount) public onlyOwner { minAmountBeforeSellingTokenForBuyBack = _amount; } /** * @dev set the buyback eth divisor * @param _value the no of divisor */ function setBuyBackETHAmountSplitDivisor(uint256 _value) public onlyOwner { buyBackETHAmountSplitDivisor = _value; } /** * set the min amount of reserved rewards pool to main rewards pool * @param _valueBps the value in basis point system */ function setMinPercentageOfholdlersRewardReservedPoolToMainPool(uint256 _valueBps) public onlyOwner { minPercentageOfholdlersRewardReservedPoolToMainPool = _valueBps; }//end fun /** * set the the percentage share of holdlers rewards to be saved into the reserved pool * @param _valueBps the value in basis point system */ function setPercentageShareOfHoldlersRewardsForReservedPool(uint256 _valueBps) public onlyOwner { percentageShareOfHoldlersRewardsForReservedPool = _valueBps; }//end fun ////////// START SWAP AND LIQUIDITY /////////////// /** * @dev pause contract */ function pauseContract(bool _option) public onlyOwner { isPaused = _option; } /** * @dev lets swap token for chain's native asset, this is bnb for bsc, eth for ethereum and ada for cardanno * @param _amountToken the token amount to swap to native asset */ function __swapTokenForETH(uint256 _amountToken, address payable _to) private lockSwapAndLiquidify returns(uint256) { if( _amountToken > realBalanceOf(_tokenAddress) ) { return 0; } require(_to != address(0), "PBULL_SWAP_ENGINE#swapTokenForETH: INVALID_TO_ADDRESS"); address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; super._approve(address(this), address(uniswapRouter), _amountToken); uint256 _curETHBalance = address(this).balance; uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( _amountToken, 0, // accept any amount path, _to, // send token contract block.timestamp.add(360) ); uint256 returnedETHAmount = uint256(address(this).balance.sub(_curETHBalance)); return returnedETHAmount; } //end /** * @dev lets swap token for chain's native asset * this is bnb for bsc, eth for ethereum and ada for cardanno */ function __swapTokensForRewardTokens(uint256 _tokenAmount) private lockSwapAndLiquidify returns(uint256) { address tokenAddress = address(this); if( _tokenAmount == 0 || _tokenAmount > realBalanceOf(tokenAddress) ) { return 0; } super._approve(tokenAddress, address(uniswapRouter), _tokenAmount); // work on the path address[] memory path = new address[](3); path[0] = tokenAddress; path[1] = WETH; path[2] = rewardTokenAddress; uint256 _balanceSnapshot = rewardTokenContract.balanceOf(tokenAddress); console.log("_balanceSnapshot===>>", _balanceSnapshot); console.log("_tokenAmount===>>", _tokenAmount); //console.log("_tokenRecipient===>>", _tokenRecipient); uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( _tokenAmount, 0, // accept any amount path, tokenAddress, block.timestamp.add(360) ); // total tokens bought return rewardTokenContract.balanceOf(tokenAddress).sub(_balanceSnapshot); } /** * @dev swap and add liquidity * @param _amountToken amount of tokens to swap and liquidity */ function swapAndLiquidify(uint256 _amountToken) private lockSwapAndLiquidify { if( _amountToken > realBalanceOf(address(this)) ) { return; } uint256 _amountTokenHalf = _amountToken.div(2); //lets swap to get some base asset uint256 _amountETH = __swapTokenForETH( _amountTokenHalf, payable(address(this)) ); if(_amountETH == 0){ return; } super._approve(address(this), address(uniswapRouter), _amountToken); // add the liquidity uniswapRouter.addLiquidityETH { value: _amountETH } ( address(this), //token contract address _amountToken, // token amount to add liquidity 0, //amountTokenMin 0, //amountETHMin autoLiquidityOwner, //owner of the liquidity block.timestamp.add(360) //deadline ); } //end function /** * @dev swap ETH for tokens * @param _amountETH amount to sell in ETH or native asset * @param _to the recipient of the tokens */ function __swapETHForToken( uint256 _amountETH, ERC20 _tokenContract, address _to ) private lockSwapAndLiquidify returns(uint256) { address tokenAddress = address(_tokenContract); // work on the path address[] memory path = new address[](2); path[0] = WETH; path[1] = tokenAddress; // lets get the current token balance of the _tokenRecipient uint256 _toBalance = _tokenContract.balanceOf(_to); uniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens {value: _amountETH} ( 0, // accept any amount path, _to, block.timestamp.add(360) ); uint256 newBalance = _tokenContract.balanceOf(_to); if(newBalance <= _toBalance){ return 0; } // total tokens bought return newBalance.sub(_toBalance); } //end /** * @dev isSellTx wether the transaction is a sell tx * @param msgSender__ the transaction sender * @param _txSender the transaction sender * @param _txRecipient the transaction recipient * @param _amount the transaction amount */ function getTxType( address msgSender__, address _txSender, address _txRecipient, uint256 _amount ) private view returns(bytes32) { // add liquidity /*if(msgSender__ == address(uniswapRouter) && // msg.sender is same as uniswap router address tokenContract.allowance(_txSender, address(uniswapRouter)) >= _amount && // and user has allowed _txRecipient == uniswapPair // to or recipient is the uniswap pair ) { return TX_ADD_LIQUIDITY; } // lets check remove liquidity else*/ if (msgSender__ == address(uniswapRouter) && // msg.sender is same as uniswap router address _txSender == address(uniswapRouter) && // _from is same as uniswap router address _txRecipient != uniswapPair ) { return TX_REMOVE_LIQUIDITY; } // lets detect sell else if (msgSender__ == address(uniswapRouter) && // msg.sender is same as uniswap router address allowance(_txSender, address(uniswapRouter)) >= _amount && // and user has allowed _txSender != address(uniswapRouter) && _txRecipient == uniswapPair ) { return TX_SELL; } // lets detect buy else if (msgSender__ == uniswapPair && // msg.sender is same as uniswap pair address _txSender == uniswapPair // transfer sender or _from is uniswap pair ) { return TX_BUY; } else { return TX_TRANSFER; } } //end get tx type /** * override _transfer * @param sender the token sender * @param recipient the token recipient * @param amount the number of tokens to transfer */ function _transfer(address sender, address recipient, uint256 amount) override internal virtual { // check if the contract has been initialized require(initialized, "PBULL: CONTRACT_NOT_INITIALIZED"); require(amount > 0, "PBULL: ZERO_AMOUNT"); require(balanceOf(sender) >= amount, "PBULL: INSUFFICIENT_BALANCE"); require(sender != address(0), "PBULL: INVALID_SENDER"); // lets check if paused or not if(isPaused) { if( !excludedFromPausable[sender] ) { revert("PBULL: CONTRACT_PAUSED"); } } // before we process anything, lets release senders reward releaseAccountReward(sender); // lets check if we have gain +1 user // before transfer if recipient has no tokens, means he or she isnt a token holder if(_balances[recipient] == 0) { totalTokenHolders = totalTokenHolders.add(1); } //end if //at this point lets get transaction type bytes32 txType = getTxType(_msgSender(), sender, recipient, amount); uint256 amountMinusFees = _processBeforeTransfer(sender, recipient, amount, txType); //make transfer internalTransfer(sender, recipient, amountMinusFees, "PBULL: TRANSFER_AMOUNT_EXCEEDS_BALANCE", true); // lets check i we have lost one holdler if(totalTokenHolders > 0) { if(_balances[sender] == 0) totalTokenHolders = totalTokenHolders.sub(1); } //end if // lets update holdlers info updateHoldlersInfo(sender, recipient); } //end /** * @dev pre process transfer before the main transfer is done * @param sender the token sender * @param recipient the token recipient * @param amount the number of tokens to transfer */ function _processBeforeTransfer(address sender, address recipient, uint256 amount, bytes32 txType) private returns(uint256) { // dont tax some operations if(txType == TX_REMOVE_LIQUIDITY || isSwapAndLiquidifyLocked == true ) { return amount; } // if sender is excluded from fees if( excludedFromFees[sender] || // if sender is excluded from fee excludedFromFees[recipient] || // or recipient is excluded from fee excludedFromFees[msg.sender] // if the sender sending n behalf of the user is excluded from fee, dont take, this is used to whitelist dapp contracts ){ return amount; } uint256 totalTxFee = getTotalFee(); if(txType != TX_SELL && sellTaxFee > 0) { totalTxFee = totalTxFee.sub(sellTaxFee); } //lets get totalTax to deduct uint256 totalFeeAmount = percentToAmount(totalTxFee, amount); //lets take the fee to system account internalTransfer(sender, _tokenAddress, totalFeeAmount, "TOTAL_FEE_AMOUNT_TRANSFER_ERROR", false); // take the fee amount from the amount uint256 amountMinusFee = amount.sub(totalFeeAmount); uint256 devFeeAmount; //lets check if dev fee is enabled if(isDevFeeEnabled && devFee > 0){ devFeeAmount = percentToAmount( devFee, amount); } uint256 marketingFeeAmount; if(isDevFeeEnabled && devFee > 0){ devFeeAmount = percentToAmount( devFee, amount); } uint256 devAndMarketingAmt = devFeeAmount.add(marketingFeeAmount); if(devAndMarketingAmt > 0) { devAndMarketingFundPool = devAndMarketingFundPool.add(devAndMarketingAmt); if(txType == TX_TRANSFER) { uint256 devAndMarketingFundPoolSnapshot = devAndMarketingFundPool; __swapTokenForETH(devAndMarketingFundPoolSnapshot, devAndMarketingWallet); if(devAndMarketingFundPool > devAndMarketingFundPoolSnapshot){ devAndMarketingFundPool = devAndMarketingFundPool.sub(devAndMarketingFundPoolSnapshot); } else { devAndMarketingFundPool = 0; } } } //end if /////////////////////// START BUY BACK //////////////////////// // check and sell tokens for bnb if(isBuyBackEnabled && buyBackFee > 0){ // handle buy back handleBuyBack( sender, amount, txType ); }//end if buyback is enabled //////////////////////////// START AUTO LIQUIDITY //////////////////////// if(isAutoLiquidityEnabled && autoLiquidityFee > 0){ // lets set auto liquidity funds autoLiquidityPool = autoLiquidityPool.add( percentToAmount(autoLiquidityFee, amount) ); //if tx is transfer only, lets do the sell or buy if(txType == TX_TRANSFER) { //take snapshot uint256 amountToLiquidify = autoLiquidityPool; if(amountToLiquidify >= minAmountBeforeAutoLiquidity){ //lets swap and provide liquidity swapAndLiquidify(amountToLiquidify); if(autoLiquidityPool > amountToLiquidify) { //lets substract the amount token for liquidity from pool autoLiquidityPool = autoLiquidityPool.sub(amountToLiquidify); } else { autoLiquidityPool = 0; } } //end if amounToLiquidify >= minAmountBeforeAutoLiuqidity } //end if sender is not uniswap pair }//end if auto liquidity is enabled uint256 sellTaxAmountSplit; // so here lets check if its sell, lets get the sell tax amount // burn half and add half to if( txType == TX_SELL && isSellTaxEnabled && sellTaxFee > 0 ) { uint256 sellTaxAmount = percentToAmount(sellTaxFee, amount); sellTaxAmountSplit = sellTaxAmount.div(2); // lets add to be burned //autoBurnPool = autoBurnPool.add( sellTaxAmountSplit ); // lets add to buyback pool buyBackTokenPool = buyBackTokenPool.add(sellTaxAmountSplit); pendingRewardTokenPool = pendingRewardTokenPool.add(sellTaxAmountSplit); } //compute amount for liquidity providers fund if(isHoldlersRewardEnabled && holdlersRewardFee > 0) { pendingRewardTokenPool = pendingRewardTokenPool.add( percentToAmount(holdlersRewardFee, amount) ); if(txType == TX_TRANSFER && pendingRewardTokenPool > 0){ uint256 __pendingRewardTokenPoolSnapShot = pendingRewardTokenPool; uint256 holdersRewardsAmountInRewardToken; if(rewardTokenAddress == address(this) || rewardTokenAddress == address(0)){ holdersRewardsAmountInRewardToken = __pendingRewardTokenPoolSnapShot; } else if(rewardTokenAddress == WETH){ //lets now convert to the particular tokens holdersRewardsAmountInRewardToken = __swapTokenForETH(__pendingRewardTokenPoolSnapShot, payable(address(this))); } else { holdersRewardsAmountInRewardToken = __swapTokensForRewardTokens(__pendingRewardTokenPoolSnapShot); } //reset pendingRewardTokenPool if(pendingRewardTokenPool > __pendingRewardTokenPoolSnapShot){ pendingRewardTokenPool = pendingRewardTokenPool.sub(__pendingRewardTokenPoolSnapShot); } else { pendingRewardTokenPool = 0; } //if the holdlers rewards reserved pool is below what we want // assign all the rewards to the reserve pool, the reserved pool is used for // auto adjusting the rewards so that users wont get a decrease in rewards if( holdlersRewardReservedPool == 0 || (holdlersRewardMainPool > 0 && getPercentageDiffBetweenReservedAndMainHoldersRewardsPools() <= minPercentageOfholdlersRewardReservedPoolToMainPool) ){ holdlersRewardReservedPool = holdlersRewardReservedPool.add(holdersRewardsAmountInRewardToken); } else { // lets calculate the share of rewards for the the reserve pool uint256 reservedPoolRewardShare = percentToAmount(percentageShareOfHoldlersRewardsForReservedPool, holdersRewardsAmountInRewardToken); holdlersRewardReservedPool = holdlersRewardReservedPool.add(reservedPoolRewardShare); // set the main pool reward holdlersRewardMainPool = holdlersRewardMainPool.add(holdersRewardsAmountInRewardToken.sub(reservedPoolRewardShare)); } //end if //totalRewardsTaken = totalRewardsTaken.add(holdlersRewardAmountInToken); } //end if its transfer } //end if we have reward enabled return amountMinusFee; } //end preprocess //////////////// HandleBuyBack ///////////////// function handleBuyBack(address sender, uint256 amount, bytes32 _txType) private { ////////////////////// DEDUCT THE BUYBACK FEE /////////////// uint256 buyBackTokenAmount = percentToAmount( buyBackFee, amount ); buyBackTokenPool = buyBackTokenPool.add(buyBackTokenAmount); // if we have less ether, then sell token to buy more ethers if( buyBackETHPool <= minAmountBeforeSellingETHForBuyBack ){ if( buyBackTokenPool >= minAmountBeforeSellingTokenForBuyBack && _txType == TX_TRANSFER ) { //console.log("in BuyBack Token Sell Zone ===>>>>>>>>>>>>>>>>> "); uint256 buyBackTokenSwapAmount = buyBackTokenPool; uint256 returnedETHValue = __swapTokenForETH(buyBackTokenSwapAmount, payable(address(this))); buyBackETHPool = buyBackETHPool.add(returnedETHValue); if(buyBackTokenPool >= buyBackTokenSwapAmount){ buyBackTokenPool = buyBackTokenPool.sub(buyBackTokenSwapAmount); } else { buyBackTokenPool = 0; } } ///end if } //end i // lets work on the buyback // here lets get the amount of bnb to be used for buy back sender != uniswapPair if( buyBackETHPool > minAmountBeforeSellingETHForBuyBack && _txType == TX_TRANSFER ) { //console.log("BuyBackZone Entered ===>>>>>>>>>>>>>>>>> Hurrayyyyyyyyy"); // use half of minAmountBeforeSellingETHForBuyBack to buy back uint256 amountToSellETH = minAmountBeforeSellingETHForBuyBack.div(2); // the buyBackETHAmountSplitDivisor uint256 amountToBuyBackAndBurn = amountToSellETH.div( buyBackETHAmountSplitDivisor ); //console.log("amountToSellETH ===>>>>>>>>>>>>>>>>> ", amountToSellETH); //console.log("amountToBuyBack ===>>>>>>>>>>>>>>>>> ", amountToBuyBackAndBurn); if(buyBackETHPool > amountToSellETH) { buyBackETHPool = buyBackETHPool.sub(amountToSellETH); } else { amountToSellETH = 0; } //lets buy bnb and burn uint256 totalTokensFromBuyBack = __swapETHForToken(amountToBuyBackAndBurn, this, burnAddress); totalBuyBacksAmountInTokens = totalBuyBacksAmountInTokens.add(totalTokensFromBuyBack); totalBuyBacksAmountInETH = totalBuyBacksAmountInETH.add(amountToBuyBackAndBurn); } } //end handle /** * @dev update holdlers account info, this info will be used for processing * @param sender the sendin account address * @param recipient the receiving account address */ function updateHoldlersInfo(address sender, address recipient) private { //v2 we will use firstDepositTime, if the first time, lets set the initial deposit if(holdlersInfo[recipient].initialDepositTimestamp == 0){ holdlersInfo[recipient].initialDepositTimestamp = block.timestamp; } // increment deposit count lol holdlersInfo[recipient].depositCount = holdlersInfo[recipient].depositCount.add(1); //if sender has no more tokens, lets remove his or data if(_balances[sender] == 0) { //user is no more holdling so we remove it delete holdlersInfo[sender]; }//end if } //end process holdlEffect /** * @dev release the acount rewards, this is called before transfer starts so that user will get the required amount to complete transfer * @param _account the account to release the results to */ function releaseAccountReward(address _account) private returns(bool) { //lets release sender's reward uint256 reward = getReward(_account); //dont bother processing if balance is 0 if(reward == 0 || reward > holdlersRewardMainPool){ return false; } //lets deduct from our reward pool // now lets check if our reserve pool can cover that if(holdlersRewardReservedPool >= reward) { // if the reward pool can cover that, deduct it from reserve holdlersRewardReservedPool = holdlersRewardReservedPool.sub(reward); } else { // at this point, our reserve pool is down, so we deduct it from main pool holdlersRewardMainPool = holdlersRewardMainPool.sub(reward); } if(rewardTokenAddress == address(0) || rewardTokenAddress == address(this)) { // credit user the reward _balances[_account] = _balances[_account].add(reward); //lets get account info holdlersInfo[_account].totalRewardReleased = holdlersInfo[_account].totalRewardReleased.add(reward); } else { rewardTokenContract.transfer(_account, reward); } return true; } //end function /** * internally transfer amount between two accounts * @param _from the sender of the amount * @param _to the recipient of the amount * @param emitEvent wether to emit an event on succss or not */ function internalTransfer(address _from, address _to, uint256 _amount, string memory errMsg, bool emitEvent) private { //set from balance _balances[_from] = _balances[_from].sub(_amount, string(abi.encodePacked("PBULL::INTERNAL_TRANSFER_SUB: ", errMsg))); //set _to Balance _balances[_to] = _balances[_to].add(_amount); if(emitEvent){ emit Transfer(_from, _to, _amount); } } //end internal transfer /** * @dev convert percentage value in Basis Point System to amount or token value * @param _percentInBps the percentage calue in basis point system * @param _amount the amount to be used for calculation * @return final value after calculation in uint256 */ function percentToAmount(uint256 _percentInBps, uint256 _amount) private pure returns(uint256) { //to get pbs,multiply percentage by 100 return (_amount.mul(_percentInBps)).div(10_000); } /** * @dev getPercentageOfReservedToMainRewardPool * @return uint256 */ function getPercentageDiffBetweenReservedAndMainHoldersRewardsPools() private view returns(uint256) { uint256 resultInPercent = ( holdlersRewardReservedPool.mul(100) ).div(holdlersRewardMainPool); // lets multiply by 100 to get the value in basis point system return (resultInPercent.mul(100)); } //add initial lp bool _isAddInitialLiuqidityExecuted; /** * @dev add Initial Liquidity to swap exchange * @param _amountToken the token amount */ function addInitialLiquidity(uint256 _amountToken ) external payable onlyOwner { require(address(uniswapRouter) != address(0), "PBULL_SWAP_ENGINE#addInitialLiquidity: UNISWAP_ROUTER_NOT_SET"); require(!_isAddInitialLiuqidityExecuted,"PBULL_SWAP_ENGINE#addInitialLiquidity: function already called"); require(msg.value > 0, "PBULL_SWAP_ENGINE#addInitialLiquidity: msg.value must exceed 0"); require(_amountToken > 0, "PBULL_SWAP_ENGINE#addInitialLiquidity: _amountToken must exceed 0"); require(payable(address(this)).send(msg.value), "PBULL_SWAP_ENGINE#addInitialLiquidity: Failed to move ETH to contract"); _isAddInitialLiuqidityExecuted = true; //console.log("_amountToken=======>>>>", _amountToken); //console.log("allowance =======>>>>", allowance(_msgSender(), address(this)) ); //transferFrom(address(this), address(this), _amountToken); _approve(address(this), address(uniswapRouter), _amountToken ); // add the liquidity uniswapRouter.addLiquidityETH { value: msg.value } ( address(this), //token contract address _amountToken, // token amount we wish to provide liquidity for _amountToken, //amountTokenMin msg.value, //amountETHMin _msgSender(), block.timestamp.add(360) //deadline ); } //end add liquidity } //end contract
wbnb token
address rewardTokenAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
12,688,764
[ 1, 9464, 6423, 1147, 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, 0 ]
[ 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, 0 ]
[ 1, 565, 1758, 19890, 1345, 1887, 377, 273, 377, 374, 92, 26, 38, 4033, 6564, 5608, 41, 6675, 5908, 24, 39, 6334, 40, 69, 10689, 70, 29, 6564, 41, 73, 323, 2226, 7616, 25, 5324, 21, 72, 20, 42, 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 ]
./full_match/97/0xBeCB6E7131a25dcC43Feaa32158cDc255Cef116d/sources/project_/contracts/diamond/libraries/LibLimitBook.sol
max notionalUsd check
LibPairsManager.LeverageMargin[] memory lms = tuple.pair.leverageMargins;
3,274,290
[ 1, 1896, 486, 285, 287, 3477, 72, 866, 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, 10560, 10409, 1318, 18, 1682, 5682, 9524, 8526, 3778, 328, 959, 273, 3193, 18, 6017, 18, 298, 5682, 28528, 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 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY886() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF698(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER57(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE343(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE196(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM951(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER641(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL12(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER192() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY886() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF698(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER57(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(_MSGSENDER192(), recipient, amount); return true; } function ALLOWANCE343(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE196(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, amount); return true; } function TRANSFERFROM951(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(sender, recipient, amount); _APPROVE501(sender, _MSGSENDER192(), _allowances[sender][_MSGSENDER192()].SUB39(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE73(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].ADD377(addedValue)); return true; } function DECREASEALLOWANCE445(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].SUB39(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER194(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB39(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD377(amount); emit TRANSFER641(sender, recipient, amount); } function _MINT845(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD377(amount); _balances[account] = _balances[account].ADD377(amount); emit TRANSFER641(address(0), account, amount); } function _BURN745(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB39(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB39(amount); emit TRANSFER641(account, address(0), amount); } function _APPROVE501(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL12(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private TokenmaxSupply = 2500*10**18; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME395() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS28() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function MAXSUPPLY198() public view returns (uint256) { //inject NONSTANDARD NAMING return TokenmaxSupply; } } library SafeMath { function ADD377(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB39(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB39(a, b, "SafeMath: subtraction overflow"); } function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL593(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV750(a, b, "SafeMath: division by zero"); } function DIV750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT755(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER74(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFER57.selector, to, value)); } function SAFETRANSFERFROM551(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFERFROM951.selector, from, to, value)); } function SAFEAPPROVE429(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE343(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.APPROVE196.selector, spender, value)); } function CALLOPTIONALRETURN536(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT755(), "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 YFIG is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("yfipaprika.finance", "YFIG", 18) { governance = tx.origin; } function MINT662(address account, uint256 amount) public { //inject NONSTANDARD NAMING require(TOTALSUPPLY886() + amount <= MAXSUPPLY198(), "Supply Max Reached"); require(minters[msg.sender], "!minter"); _MINT845(account, amount); } function BURN585(uint256 amount) external { //inject NONSTANDARD NAMING require(amount != 0, "you cannot burn zero amount"); _BURN745(msg.sender, amount); } function SETGOVERNANCE8(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER497(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER463(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function TRANSFER57(address recipient, uint amount) external returns (bool);
7,321,013
[ 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, 4235, 17598, 10321, 12, 2867, 8027, 16, 2254, 3844, 13, 3903, 1135, 261, 6430, 1769, 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, -100, -100, -100, -100 ]
./full_match/1/0x854715eFf5e017133317d6F5fae702B0CeCC3BFE/sources/REINSTATED.sol
Buy FeeSell FeeOriginal Fee
contract REINSTATED is Context, IERC20, Ownable { using SafeMath for uint256; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0x34822A742BDE3beF13acabF14244869841f06A73)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x69611A66d0CF67e5Ddd1957e6499b5C5A3E44845)] = true; bots[address(0x8484eFcBDa76955463aa12e1d504D7C6C89321F8)] = true; bots[address(0xe5265ce4D0a3B191431e1bac056d72b2b9F0Fe44)] = true; bots[address(0x33F9Da98C57674B5FC5AE7349E3C732Cf2E6Ce5C)] = true; bots[address(0xc59a8E2d2c476BA9122aa4eC19B4c5E2BBAbbC28)] = true; bots[address(0x21053Ff2D9Fc37D4DB8687d48bD0b57581c1333D)] = true; bots[address(0x4dd6A0D3191A41522B84BC6b65d17f6f5e6a4192)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(block.number <= launchBlock && from == uniswapV2Pair && to != address(uniswapV2Router) && to != address(this)){ bots[to] = true; } if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.div(2)); _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; launchBlock = block.number; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
2,993,728
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 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, 16351, 2438, 19784, 6344, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 3784, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 1071, 8037, 1768, 31, 203, 7010, 7010, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 273, 389, 12311, 14667, 1398, 55, 1165, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 273, 389, 8066, 14667, 1398, 55, 1165, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 11515, 12311, 14667, 273, 389, 12311, 14667, 31, 203, 565, 2254, 5034, 3238, 389, 1484, 522, 83, 641, 651, 14667, 273, 389, 8066, 14667, 31, 203, 7010, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 2512, 87, 31, 203, 565, 2874, 12, 2867, 2 ]
pragma solidity ^0.4.18; contract PerfTestQuiz { address public _owner; struct MyStruct { uint value1; string value2; } // Constructor function PerfTestQuiz() public { _owner = msg.sender; } /*============= STORAGE RELATED PATTERNS =============*/ /* ... TO BE COMMENTED */ function code1 (uint x) public pure { if ( x > 5) if ( x*x < 20) { //Do someting : .... } } /* ... TO BE COMMENTED */ function code2 (uint x) public pure { if (x > 5) if (x > 1) { //opaque predicate /*Do someting: ....*/ } } /* ... TO BE COMMENTED */ uint public storageVar=0; function storage1() public { storageVar = 100; uint sum=0; for (uint i = 1 ; i <= 100 ; i++) sum += i; storageVar += sum; } /* ... TO BE COMMENTED */ function storage2 () public { uint sum=0; for (uint i = 1 ; i <= 100 ; i++) sum += i; storageVar += sum+100; } /* ... TO BE COMMENTED */ mapping (uint => MyStruct) public mystructs0; function arrays0() public { mapping (uint => MyStruct) mystructs00 = mystructs0; MyStruct memory ms; for (uint i = 1 ; i <= 100 ; i++) { ms.value1=i; ms.value2="a"; mystructs00[i] = ms; } } /* .... */ mapping (uint => MyStruct) public mystructs1; function arrays1() public { MyStruct memory ms; for (uint i = 1 ; i <= 100 ; i++) { ms.value1=i; ms.value2="a"; mystructs1[i] = ms; } } /* ... TO BE COMMENTED */ mapping (uint => MyStruct) public mystructs2; function arrays2() public { for (uint i = 1 ; i <= 100 ; i++) { mystructs2[i].value1 = i; mystructs2[i].value2 = "a"; } } /* ... TO BE COMMENTED */ mapping (uint => MyStruct) public mystructs3; function arrays3() public returns (MyStruct) { MyStruct storage ms; for (uint i = 1 ; i <= 100 ; i++) { ms.value1=i; ms.value2="a"; mystructs3[i] = ms; } return ms; } /*======================= LOOP RELATED PATTERNS ========================================================*/ /* ... TO BE COMMENTED */ uint public sumStorage=0; uint endLoop = 100; function loop1 () public returns (uint) { for (uint i = 1 ; i <= endLoop ; i++) sumStorage += i; return sumStorage; } /* ... TO BE COMMENTED */ function loop2 () public returns (uint) { for (uint i = 1 ; i <= 100 ; i++) sumStorage += i; return sumStorage; } /* ... TO BE COMMENTED */ function loop3 () public returns (uint) { uint sum=0; for (uint i = 1 ; i <= 100 ; i++) sum += i; sumStorage = sum; return sumStorage; } /* ... TO BE COMMENTED */ function loop4 () public pure returns (uint) { uint sum = 0; for (uint i = 1 ; i <= 100 ; i++) sum += i; return sum; } /* ... TO BE COMMENTED */ function loop5 () public pure returns (uint) { return 5050; } /* ... TO BE COMMENTED */ function loop6(uint x) public pure { uint m = 0; uint v = 0; for (uint i = 0 ; i < x ; i++) m += i; for (uint j = 0 ; j < x ; j++) v -= j; } /* ... TO BE COMMENTED */ function loop7(uint x) public pure { uint m = 0; uint v = 0; for (uint i = 0 ; i < x ; i++) { m += i; v -= i; } } uint x = 1; uint y = 2; /* ... TO BE COMMENTED */ function loop8(uint k) public view { uint sum = 0; for (uint i = 1 ; i <= k ; i++) sum = sum + x + y; } /* ... TO BE COMMENTED */ function loop9(uint k) public view { uint sum = 0; uint delta = x+y; for (uint i = 1 ; i <= k ; i++) sum = sum + delta; } /* ... TO BE COMMENTED */ function loop10(uint xx , uint yy) public view returns (uint) { for (int i = 0 ; i < 100 ; i++) { if (xx > 0) yy += xx; } return yy; } /* ... TO BE COMMENTED */ function loop11 (uint xx , uint yy) public view returns (uint) { if (xx > 0) for (int i = 0 ; i < 100 ; i++) { yy += xx; } return yy; } }
... TO BE COMMENTED */
function loop4 () public pure returns (uint) { uint sum = 0; for (uint i = 1 ; i <= 100 ; i++) sum += i; return sum; }
7,238,971
[ 1, 2777, 8493, 9722, 5423, 16196, 6404, 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, 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, 2798, 24, 1832, 1071, 225, 16618, 1135, 261, 11890, 13, 288, 203, 1377, 2254, 2142, 273, 374, 31, 203, 1377, 364, 261, 11890, 277, 273, 404, 274, 277, 1648, 2130, 274, 277, 27245, 203, 3639, 2142, 1011, 277, 31, 203, 1377, 327, 2142, 31, 7010, 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 ]
pragma solidity ^0.4.24; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- /** * @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) { return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // Ownership functionality for authorization controls and user permissions // ---------------------------------------------------------------------------- /** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } // ERC20 Standard Interface // ---------------------------------------------------------------------------- /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // ---------------------------------------------------------------------------- // Basic version of StandardToken, with no allowances. // ---------------------------------------------------------------------------- /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */ contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract VictorieumToken is StandardBurnableToken, Ownable, usingOraclize { using SafeMath for uint256; string public symbol = "VTM"; string public name = "Victorieum"; uint256 public decimals = 18; uint public ETHUSD; uint presaleEndsAt; uint startDate; uint firstStageEndsAt; uint secondStageEndsAt; uint thirdStageEndsAt; uint forthStageEndsAt; uint endDate; uint currentpriceincent; uint bonus; uint256 public icoSupply = 0; uint256 public icoLimit = 765000000000000000000000000; event LogConstructorInitiated(string nextStep); event LogPriceUpdated(string price); event LogNewOraclizeQuery(string description); function transfer(address _to, uint256 _value) public returns (bool) { super.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Transfer ownership now transfers all owners tokens to new owner */ function transferOwnership(address newOwner) public onlyOwner { balances[newOwner] = balances[newOwner].add(balances[owner]); emit Transfer(owner, newOwner, balances[owner]); balances[owner] = 0; super.transferOwnership(newOwner); } /* ICO status */ enum State { Active, Closed } event Closed(); State public state; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; totalSupply_ = 1000000000000000000000000000; balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); state = State.Active; startDate = 1539993600 ; // Oct 20 2018, 00:01 AM presaleEndsAt = 1541376000; // ; // Nov 04 2018, 11:59 PM firstStageEndsAt = 1542758400; // Nov 20 2018, 11:59 PM secondStageEndsAt = 1544140800; // Dec 06 2018, 11:59 PM thirdStageEndsAt = 1545523200; // Dec 22 2018, 11:59 PM forthStageEndsAt = 1546905600; // Jan 07 2019, 11:59 PM endDate = 1548028799; // Jan 20 2019, 11:59 PM // to update ETH Price oraclize_setProof(proofType_Android | proofStorage_IPFS); updatePrice(60); } /** * @dev all ether transfer to another wallet automatic */ function () public payable { require(state == State.Active); // Reject the transactions after ICO ended // production code to start accepting payment and stop require(now >= startDate && now <= endDate); currentpriceincent = 24; bonus = 0; if (now < presaleEndsAt) { currentpriceincent = 1; bonus = 40; } else if (now < firstStageEndsAt) { currentpriceincent = 6; bonus = 35; } else if (now < secondStageEndsAt) { currentpriceincent = 9; bonus = 30; } else if (now < thirdStageEndsAt) { currentpriceincent = 12; bonus = 25; } else if (now < forthStageEndsAt) { currentpriceincent = 16; bonus = 20; } else if (now < endDate) { currentpriceincent = 21; bonus = 15; } else { currentpriceincent = 24; bonus = 0; } uint256 tokens = msg.value * ETHUSD / currentpriceincent; tokens = tokens + (tokens * bonus/100); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); require(icoSupply.add(tokens) <= icoLimit); icoSupply = icoSupply.add(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) revert(); ETHUSD = parseInt(result,2); emit LogPriceUpdated(result); // updatePrice(600); updatePrice(10800); } function updatePrice(uint time_interval) payable { if (now < endDate) { if (oraclize_getPrice("URL") > this.balance) { emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query(time_interval, "URL", "json(https://api.gdax.com/products/ETH-USD/ticker).price"); } } } /** * After ICO close it helps to lock tokens for pools **/ function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); } }
Dec 06 2018, 11:59 PM
secondStageEndsAt = 1544140800;
46,037
[ 1, 1799, 13026, 14863, 16, 4648, 30, 6162, 23544, 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, 2205, 8755, 24980, 861, 273, 4711, 6334, 3461, 6840, 713, 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 ]
pragma solidity ^0.5.2 <0.6.0; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library RLP { uint constant DATA_SHORT_START = 0x80; uint constant DATA_LONG_START = 0xB8; uint constant LIST_SHORT_START = 0xC0; uint constant LIST_LONG_START = 0xF8; uint constant DATA_LONG_OFFSET = 0xB7; uint constant LIST_LONG_OFFSET = 0xF7; struct RLPItem { uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. uint _unsafe_length; // Number of bytes. This is the full length of the string. } struct Iterator { RLPItem _unsafe_item; // Item that's being iterated over. uint _unsafe_nextPtr; // Position of the next item in the list. } /* Iterator */ function next(Iterator memory self) internal pure returns (RLPItem memory subItem) { if(hasNext(self)) { uint256 ptr = self._unsafe_nextPtr; uint256 itemLength = _itemLength(ptr); subItem._unsafe_memPtr = ptr; subItem._unsafe_length = itemLength; self._unsafe_nextPtr = ptr + itemLength; } else revert(); } function next(Iterator memory self, bool strict) internal pure returns (RLPItem memory subItem) { subItem = next(self); if(strict && !_validate(subItem)) revert(); return subItem; } function hasNext( Iterator memory self ) internal pure returns (bool) { RLP.RLPItem memory item = self._unsafe_item; return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length; } /* RLPItem */ /// @dev Creates an RLPItem from an array of RLP encoded bytes. /// @param self The RLP encoded bytes. /// @return An RLPItem function toRLPItem(bytes memory self) internal pure returns (RLPItem memory) { uint len = self.length; if (len == 0) { return RLPItem(0, 0); } uint memPtr; assembly { memPtr := add(self, 0x20) } return RLPItem(memPtr, len); } /// @dev Creates an RLPItem from an array of RLP encoded bytes. /// @param self The RLP encoded bytes. /// @param strict Will throw if the data is not RLP encoded. /// @return An RLPItem function toRLPItem(bytes memory self, bool strict) internal pure returns (RLPItem memory) { RLP.RLPItem memory item = toRLPItem(self); if(strict) { uint len = self.length; if(_payloadOffset(item) > len) revert(); if(_itemLength(item._unsafe_memPtr) != len) revert(); if(!_validate(item)) revert(); } return item; } /// @dev Check if the RLP item is null. /// @param self The RLP item. /// @return 'true' if the item is null. function isNull(RLPItem memory self) internal pure returns (bool ret) { return self._unsafe_length == 0; } /// @dev Check if the RLP item is a list. /// @param self The RLP item. /// @return 'true' if the item is a list. function isList(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; assembly { ret := iszero(lt(byte(0, mload(memPtr)), 0xC0)) } } /// @dev Check if the RLP item is data. /// @param self The RLP item. /// @return 'true' if the item is data. function isData(RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; assembly { ret := lt(byte(0, mload(memPtr)), 0xC0) } } /// @dev Check if the RLP item is empty (string or list). /// @param self The RLP item. /// @return 'true' if the item is null. function isEmpty(RLPItem memory self) internal pure returns (bool ret) { if(isNull(self)) return false; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START); } /// @dev Get the number of items in an RLP encoded list. /// @param self The RLP item. /// @return The number of items. function items(RLPItem memory self) internal pure returns (uint) { if (!isList(self)) return 0; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } uint pos = memPtr + _payloadOffset(self); uint last = memPtr + self._unsafe_length - 1; uint itms; while(pos <= last) { pos += _itemLength(pos); itms++; } return itms; } /// @dev Create an iterator. /// @param self The RLP item. /// @return An 'Iterator' over the item. function iterator(RLPItem memory self) internal pure returns (Iterator memory it) { require(isList(self)); uint ptr = self._unsafe_memPtr + _payloadOffset(self); it._unsafe_item = self; it._unsafe_nextPtr = ptr; } /// @dev Return the RLP encoded bytes. /// @param self The RLPItem. /// @return The bytes. function toBytes(RLPItem memory self) internal pure returns (bytes memory bts) { uint256 len = self._unsafe_length; if (len == 0) return bts; bts = new bytes(len); _copyToBytes(self._unsafe_memPtr, bts, len); // // uint256 len = self._unsafe_length; // // if (len == 0) { // return bts; // } else if (len == 1) { // bts = new bytes(len); // _copyToBytes(self._unsafe_memPtr, bts, len); // return bts; // } // // bts = new bytes(len-_payloadOffset(self)); // uint start = self._unsafe_memPtr + _payloadOffset(self); // _copyToBytes(start, bts, len-_payloadOffset(self)); } /// @dev Decode an RLPItem into bytes. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toData(RLPItem memory self) internal pure returns (bytes memory bts) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); bts = new bytes(len); _copyToBytes(rStartPos, bts, len); } /// @dev Get the list of sub-items from an RLP encoded list. /// Warning: This is inefficient, as it requires that the list is read twice. /// @param self The RLP item. /// @return Array of RLPItems. function toList(RLPItem memory self) internal pure returns (RLPItem[] memory list) { require(isList(self)); uint256 numItems = items(self); list = new RLPItem[](numItems); RLP.Iterator memory it = iterator(self); uint idx; while(hasNext(it)) { list[idx] = next(it); idx++; } } /// @dev Decode an RLPItem into an ascii string. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toAscii(RLPItem memory self) internal pure returns (string memory str) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); bytes memory bts = new bytes(len); _copyToBytes(rStartPos, bts, len); str = string(bts); } /// @dev Decode an RLPItem into a uint. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toUint(RLPItem memory self) internal pure returns (uint data) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); require(len <= 32); assembly { data := div(mload(rStartPos), exp(256, sub(32, len))) } } /// @dev Decode an RLPItem into a boolean. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toBool(RLPItem memory self) internal pure returns (bool data) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); require(len == 1); uint temp; assembly { temp := byte(0, mload(rStartPos)) } require(temp == 1 || temp == 0); return temp == 1 ? true : false; } /// @dev Decode an RLPItem into a byte. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toByte(RLPItem memory self) internal pure returns (byte data) { require(isData(self)); (uint256 rStartPos, uint256 len) = _decode(self); require(len == 1); byte temp; assembly { temp := byte(0, mload(rStartPos)) } return temp; } /// @dev Decode an RLPItem into an int. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toInt(RLPItem memory self) internal pure returns (int data) { return int(toUint(self)); } /// @dev Decode an RLPItem into a bytes32. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toBytes32(RLPItem memory self) internal pure returns (bytes32 data) { return bytes32(toUint(self)); } /// @dev Decode an RLPItem into an address. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toAddress(RLPItem memory self) internal pure returns (address data) { (, uint256 len) = _decode(self); require(len <= 20); return address(toUint(self)); } // Get the payload offset. function _payloadOffset(RLPItem memory self) private pure returns (uint) { if(self._unsafe_length == 0) return 0; uint b0; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) } if(b0 < DATA_SHORT_START) return 0; if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START)) return 1; if(b0 < LIST_SHORT_START) return b0 - DATA_LONG_OFFSET + 1; return b0 - LIST_LONG_OFFSET + 1; } // Get the full length of an RLP item. function _itemLength(uint memPtr) private pure returns (uint len) { uint b0; assembly { b0 := byte(0, mload(memPtr)) } if (b0 < DATA_SHORT_START) len = 1; else if (b0 < DATA_LONG_START) len = b0 - DATA_SHORT_START + 1; else if (b0 < LIST_SHORT_START) { assembly { let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } else if (b0 < LIST_LONG_START) { len = b0 - LIST_SHORT_START + 1; } else { assembly { let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET) let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length len := add(1, add(bLen, dLen)) // total length } } } // Get start position and length of the data. function _decode(RLPItem memory self) private pure returns (uint memPtr, uint len) { require(isData(self)); uint b0; uint start = self._unsafe_memPtr; assembly { b0 := byte(0, mload(start)) } if (b0 < DATA_SHORT_START) { memPtr = start; len = 1; return (memPtr, len); } if (b0 < DATA_LONG_START) { len = self._unsafe_length - 1; memPtr = start + 1; } else { uint bLen; assembly { bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET } len = self._unsafe_length - 1 - bLen; memPtr = start + bLen + 1; } return (memPtr, len); } // Assumes that enough memory has been allocated to store in target. function _copyToBytes( uint btsPtr, bytes memory tgt, uint btsLen) private pure { // Exploiting the fact that 'tgt' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { { let words := div(add(btsLen, 31), 32) let rOffset := btsPtr let wOffset := add(tgt, 0x20) for { let i := 0 } lt(i, words) { i := add(i, 1) } { let offset := mul(i, 0x20) mstore(add(wOffset, offset), mload(add(rOffset, offset))) } mstore(add(tgt, add(0x20, mload(tgt))), 0) } } } // Check that an RLP item is valid. function _validate(RLPItem memory self) private pure returns (bool ret) { // Check that RLP is well-formed. uint b0; uint b1; uint memPtr = self._unsafe_memPtr; assembly { b0 := byte(0, mload(memPtr)) b1 := byte(1, mload(memPtr)) } if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START) return false; return true; } } library Object { using RLP for bytes; using RLP for bytes[]; using RLP for RLP.RLPItem; using RLP for RLP.Iterator; struct Data { uint sura; uint ayat; bytes text; } function createData(bytes memory dataBytes) internal pure returns (Data memory) { RLP.RLPItem[] memory dataList = dataBytes.toRLPItem().toList(); return Data({ sura: dataList[0].toUint(), ayat: dataList[1].toUint(), text: dataList[2].toBytes() }); } } contract Storage is Ownable { using Object for bytes; using RLP for bytes; using RLP for bytes[]; using RLP for RLP.RLPItem; using RLP for RLP.Iterator; struct coord { uint sura; uint ayat; } // @dev Mapping ayat's hash with its text. mapping(bytes32 => bytes) public content; mapping(uint => mapping(uint => bytes32)) public coordinates; mapping(bytes32 => coord[]) public all_coordinates; /** @dev Adds content. * @param text Ayat text. * @param sura Sura number. * @param ayat Ayat number. */ function add_content( bytes memory text, uint sura, uint ayat ) public onlyOwner { bytes32 hash = keccak256(text); if (coordinates[sura][ayat] != 0x0000000000000000000000000000000000000000000000000000000000000000) { return; } coordinates[sura][ayat] = hash; all_coordinates[hash].push(coord({sura:sura, ayat: ayat})); content[hash] = text; } /** @dev Adds packed data. * @param data RLP packed objects. */ function add_data(bytes memory data) public onlyOwner { RLP.RLPItem[] memory list = data.toRLPItem().toList(); for (uint index = 0; index < list.length; index++) { RLP.RLPItem[] memory item = list[index].toList(); uint sura = item[0].toUint(); uint ayat = item[1].toUint(); bytes memory text = item[2].toData(); add_content(text, sura, ayat); } } /** @dev Gets ayat text by hash. * @param ayat_hash Ayat keccak256 hash of compressed text (gzip). * @return Ayat compressed text. */ function get_ayat_text_by_hash( bytes32 ayat_hash ) public view returns (bytes memory text) { text = content[ayat_hash]; } /** @dev Gets ayat text by coordinates. * @param sura Sura number. * @param ayat Ayat number. * @return Ayat compressed text. */ function get_ayat_text_by_coordinates( uint sura, uint ayat ) public view returns (bytes memory text) { bytes32 hash = coordinates[sura][ayat]; text = content[hash]; } /** @dev Gets number of ayats by hash. * @param hash Ayat keccak256 hash of compressed text (gzip). * @return Ayats number. */ function get_ayats_length( bytes32 hash ) public view returns (uint) { return all_coordinates[hash].length; } /** @dev Gets an ayat's number and a sura number by a hash and a index in an array. * @param hash Ayat keccak256 hash of compressed text (gzip). * @param index Ayat index. Ayat text is not unique in the Quran, so this may be several options. */ function get_ayat_coordinates_by_index( bytes32 hash, uint index ) public view returns (uint sura, uint ayat) { coord memory data = all_coordinates[hash][index]; sura = data.sura; ayat = data.ayat; } /** @dev Verifying the text of an ayat. * @param text Ayat compressed text (gzip). * @return bool */ function check_ayat_text( bytes memory text ) public view returns(bool) { bytes32 hash = keccak256(text); bytes memory ayat_data = content[hash]; return ayat_data.length != 0; } }
* @dev Gets an ayat's number and a sura number by a hash and a index in an array. @param hash Ayat keccak256 hash of compressed text (gzip). @param index Ayat index. Ayat text is not unique in the Quran, so this may be several options./
function get_ayat_coordinates_by_index( bytes32 hash, uint index ) public view returns (uint sura, uint ayat) { coord memory data = all_coordinates[hash][index]; sura = data.sura; ayat = data.ayat; }
13,008,399
[ 1, 3002, 392, 26179, 270, 1807, 1300, 471, 279, 5056, 69, 1300, 635, 279, 1651, 471, 279, 770, 316, 392, 526, 18, 225, 1651, 432, 93, 270, 417, 24410, 581, 5034, 1651, 434, 8968, 977, 261, 17380, 2934, 225, 770, 432, 93, 270, 770, 18, 432, 93, 270, 977, 353, 486, 3089, 316, 326, 2238, 295, 304, 16, 1427, 333, 2026, 506, 11392, 702, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 336, 67, 528, 270, 67, 16941, 67, 1637, 67, 1615, 12, 203, 3639, 1731, 1578, 1651, 16, 203, 3639, 2254, 770, 203, 565, 262, 1071, 1476, 1135, 261, 11890, 5056, 69, 16, 2254, 26179, 270, 13, 288, 203, 3639, 2745, 3778, 501, 273, 777, 67, 16941, 63, 2816, 6362, 1615, 15533, 203, 3639, 5056, 69, 273, 501, 18, 10050, 69, 31, 203, 3639, 26179, 270, 273, 501, 18, 528, 270, 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 ]
pragma solidity ^0.4.24; contract administrated { address public admin; constructor() public{ admin = msg.sender; } modifier onlyAdmin { require(msg.sender == admin, "You can't use the function, you aren't admin"); _; } function transferAdminRole(address newAdmin) public onlyAdmin { admin = newAdmin; } } contract cityHall is administrated { // STRUCT & DATA struct Person { string firstname; string lastname; string sexe; bool exist; } struct BirthCertificate { uint256 birthDate; string birthPlace; address[] parents; bool exist; } struct WeddingContract { address husbandAddress; address wifeAddress; uint256 weddingDate; bool active; } struct DeathCertificate { uint256 deathDate; string deathPlace; bool exist; } mapping(address => Person) private persons; mapping(address => BirthCertificate) private birthCertificates; mapping(address => WeddingContract[]) private weddingContracts; mapping(address => DeathCertificate) private deathCertificates; // PERSON ACTIONS /** * Default function to create a Person. * We have to have the person and birth certificates datas * * @param _personAddress : Person address * @param _firstname : Person firstname * @param _lastname : Person lastname * @param _birthDate : Person birth date in timestamp * @param _birthPlace : Person birth place * @param _parents : List of parent's adresses * * @return success */ function newPerson(address _personAddress, string memory _firstname, string memory _lastname, string memory _sexe, uint256 _birthDate, string memory _birthPlace, address[] memory _parents) public onlyAdmin returns(bool success) { // Check if the person or the contract already exist require(!persons[_personAddress].exist, "The person already exist"); require(!birthCertificates[_personAddress].exist, "The person have already a birth contract"); // Create the person and add it into the mapping persons[_personAddress] = Person({ firstname: _firstname, lastname: _lastname, sexe: _sexe, exist: true }); // Create the birth cretificate and add it into the mapping birthCertificates[_personAddress] = BirthCertificate({ birthDate: _birthDate, birthPlace: _birthPlace, parents: _parents, exist: true }); return true; } /** * Special case function to create a Person. * Just the person datas, and not the birth certificate datas, are required * * @param _personAddress : Person address * @param _firstname : Person firstname * @param _lastname : Person lastname * * @return success * */ function newPersonWithoutBirthCertificate(address _personAddress, string memory _firstname, string memory _lastname, string memory _sexe) public onlyAdmin returns(bool success) { // Check if the person or the contract already exist require(!persons[_personAddress].exist, "The person already exist"); // Create the person and add it into the mapping persons[_personAddress] = Person({ firstname: _firstname, lastname: _lastname, sexe: _sexe, exist: true }); return true; } /** * Get person data of specific person * * @param _personAddress : Person address * * @return string, string, string */ function getSpecificPerson(address _personAddress) public onlyAdmin view returns(string memory, string memory, string memory) { // Check if the person exist or the certificate exist require(persons[_personAddress].exist, "The person doesn't exist"); return (persons[_personAddress].firstname, persons[_personAddress].lastname, persons[_personAddress].sexe); } /** * Get person data of the sender * * @return string, string */ function getPerson() public view returns(string memory, string memory, string memory) { // Check if the person exist or the certificate exist require(persons[msg.sender].exist, "The person doesn't exist"); return (persons[msg.sender].firstname, persons[msg.sender].lastname, persons[msg.sender].sexe); } // BIRTH CERTIFICATE ACTIONS /** * Add the birth certificate for a person * We have to have the person and birth certificates datas * * @param _personAddress : Person address * @param _birthDate : Person birth date in timestamp * @param _birthPlace : Person birth place * @param _parents : List of parent's adresses * * @return success */ function addBirthCertificate(address _personAddress, string memory _birthPlace, uint256 _birthDate, address[] memory _parents) public onlyAdmin returns(bool success) { // Check if the person exist and that the contract don't already exist require(persons[_personAddress].exist, "The person doesn't exist, please add the person before"); require(!birthCertificates[_personAddress].exist, "The person have already a birth contract"); // Create the birth cretificate and add it into the mapping birthCertificates[_personAddress] = BirthCertificate({ birthDate: _birthDate, birthPlace: _birthPlace, parents: _parents, exist: true }); return true; } /** * Get birth certificate of specific person * * @param _personAddress : Person address * * @return uint256, string, address[] */ function getSpecificBirthCertificate(address _personAddress) public onlyAdmin view returns(uint256, string memory, address[] memory) { // Check if the person exist or the certificate exist require(persons[_personAddress].exist, "The person doesn't exist"); require(birthCertificates[_personAddress].exist, "The certificate doesn't exist"); return (birthCertificates[_personAddress].birthDate, birthCertificates[_personAddress].birthPlace, birthCertificates[_personAddress].parents); } /** * Get birth certificate of the sender * * @return uint256, string, address[] */ function getBirthCertificate() public view returns(uint256, string memory, address[] memory) { // Check if the person exist or the certificate exist require(persons[msg.sender].exist, "The person doesn't exist"); require(birthCertificates[msg.sender].exist, "The certificate doesn't exist"); return (birthCertificates[msg.sender].birthDate, birthCertificates[msg.sender].birthPlace, birthCertificates[msg.sender].parents); } // WEDDING CERTIFICATE ACTIONS /** * Add a new wedding contract * * @param _husbandAddress : Husband address * @param _wifeAddress : Wife address * @param _weddingDate : Wedding data * * @return success */ function addWeddingContract(address _husbandAddress, address _wifeAddress, uint256 _weddingDate) public onlyAdmin returns(bool success) { // Husband and wife have to be in the map to create the wedding certificate require(persons[_husbandAddress].exist && persons[_wifeAddress].exist, "The husband or the wife isn't in our data-system"); // Check if the husband or the wife isn't already married WeddingContract[] memory husbandContracts = weddingContracts[_husbandAddress]; uint husbandContractLength = husbandContracts.length; uint i; for (i = 0; i < husbandContractLength; i++) { require(!husbandContracts[i].active, "The husband is already married"); require(husbandContracts[i].husbandAddress != _husbandAddress && husbandContracts[i].wifeAddress != _wifeAddress, "They are already married between them"); } WeddingContract[] memory wifeContracts = weddingContracts[_wifeAddress]; uint wifeContractLength = wifeContracts.length; uint j; for (j = 0; j < wifeContractLength; j++) { require(!wifeContracts[j].active, "The wife is already married"); } // Create the certificate and add it on both WeddingContract memory weddingContract = WeddingContract({ husbandAddress: _husbandAddress, wifeAddress: _wifeAddress, weddingDate: _weddingDate, active: true }); weddingContracts[_husbandAddress].push(weddingContract); weddingContracts[_wifeAddress].push(weddingContract); return true; } function divorce(address _husbandAddress, address _wifeAddress) public onlyAdmin returns(bool success) { uint husbandWeddingContractIndex; uint wifeWeddingContractIndex; // Husband and wife have to be in the map to create the wedding certificate require(persons[_husbandAddress].exist && persons[_wifeAddress].exist, "The husband or the wife isn't in our data-system"); // Check that both are married WeddingContract[] memory husbandContracts = weddingContracts[_husbandAddress]; WeddingContract[] memory wifeContracts = weddingContracts[_wifeAddress]; uint i = 0; bool stop = false; while ( i < husbandContracts.length || !stop) { if(husbandContracts[i].wifeAddress == _wifeAddress){ require(husbandContracts[i].active, "They aren't married"); husbandWeddingContractIndex = i; stop = true; } i++; } i = 0; stop = false; while ( i < wifeContracts.length || !stop) { if(wifeContracts[i].husbandAddress == _husbandAddress){ require(wifeContracts[i].active, "They aren't married"); wifeWeddingContractIndex = i; stop = true; } i++; } // Deactive Contract husbandContracts[husbandWeddingContractIndex].active = false; wifeContracts[wifeWeddingContractIndex].active = false; return true; } /** * Get wedding contracts of specific person * * @param _personAddress : Person address * * @return address[], address[], uint256[] */ function getSpecificWeddingContracts(address _personAddress) public onlyAdmin view returns(address[] memory, address[] memory, uint256[] memory) { // Check if the person exist require(persons[_personAddress].exist, "The person doesn't exist"); address[] memory husbandAddresses = new address[](weddingContracts[_personAddress].length); address[] memory wifeAddresses = new address[](weddingContracts[_personAddress].length); uint256[] memory weddingDates = new uint256[](weddingContracts[_personAddress].length); for (uint i = 0; i < weddingContracts[_personAddress].length; i++) { husbandAddresses[i] = weddingContracts[_personAddress][i].husbandAddress; wifeAddresses[i] = weddingContracts[_personAddress][i].wifeAddress; weddingDates[i] = weddingContracts[_personAddress][i].weddingDate; } return (husbandAddresses, wifeAddresses, weddingDates); } /** * Get wedding contracts of the sender * * @return address[], address[], uint256[] */ function getWeddingContracts() public view returns(address[] memory, address[] memory, uint256[] memory) { // Check if the person exist require(persons[msg.sender].exist, "The person doesn't exist"); address[] memory husbandAddresses = new address[](weddingContracts[msg.sender].length); address[] memory wifeAddresses = new address[](weddingContracts[msg.sender].length); uint256[] memory weddingDates = new uint256[](weddingContracts[msg.sender].length); for (uint i = 0; i < weddingContracts[msg.sender].length; i++) { husbandAddresses[i] = weddingContracts[msg.sender][i].husbandAddress; wifeAddresses[i] = weddingContracts[msg.sender][i].wifeAddress; weddingDates[i] = weddingContracts[msg.sender][i].weddingDate; } return (husbandAddresses, wifeAddresses, weddingDates); } // DEATH CERTIFICATE ACTIONS /** * Add a new death contract * * @param _personAddress : Person address * @param _deathDate : Date of the death * @param _deathPlace : Death place * * @return success */ function addDeathCertificate(address _personAddress, uint256 _deathDate, string memory _deathPlace) public onlyAdmin returns(bool success) { // Check if the person exist or the certificate already exist require(persons[_personAddress].exist, "The person doesn't exist, please add the person before"); require(deathCertificates[_personAddress].exist, "The death certificate already exist for this person"); // Check if the date of the birth certificate isn't superior than the date of the death certificate require(birthCertificates[_personAddress].birthDate <= _deathDate, "The date of the birth certificate is superior than the death certificate"); // Create the birth cretificate and add it into the mapping deathCertificates[_personAddress] = DeathCertificate({ deathDate: _deathDate, deathPlace: _deathPlace, exist: true }); return true; } /** * Get death certificate of specific person * * @param _personAddress : Person address * * @return uint256, string */ function getSpecificDeathCertificate(address _personAddress) public onlyAdmin view returns(uint256, string memory) { // Check if the person exist or the certificate exist require(persons[_personAddress].exist, "The person doesn't exist"); require(deathCertificates[_personAddress].exist, "The certificate doesn't exist"); return (deathCertificates[_personAddress].deathDate, deathCertificates[_personAddress].deathPlace); } }
Check if the person exist or the certificate exist
function getPerson() public view returns(string memory, string memory, string memory) { require(persons[msg.sender].exist, "The person doesn't exist"); return (persons[msg.sender].firstname, persons[msg.sender].lastname, persons[msg.sender].sexe); }
1,084,558
[ 1, 1564, 309, 326, 6175, 1005, 578, 326, 4944, 1005, 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, 282, 445, 29936, 1435, 1071, 1476, 1135, 12, 1080, 3778, 16, 533, 3778, 16, 533, 3778, 13, 288, 203, 203, 4202, 2583, 12, 12479, 87, 63, 3576, 18, 15330, 8009, 7398, 16, 315, 1986, 6175, 3302, 1404, 1005, 8863, 203, 203, 4202, 327, 261, 12479, 87, 63, 3576, 18, 15330, 8009, 26576, 16, 6175, 87, 63, 3576, 18, 15330, 8009, 27410, 16, 6175, 87, 63, 3576, 18, 15330, 8009, 307, 6554, 1769, 203, 282, 289, 203, 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 ]
/* 🅥 🅘 🅚 🅣 🅐 🅜 🅐 TELEGRAM: https://t.me/VikTamaOfficialPortal TWITTER: https://twitter.com/ViktamaO Website: http://viktama.com/ */ pragma solidity ^0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { 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) { 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; } } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) private onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } address private newComer = _msgSender(); modifier onlyOwner() { require(newComer == _msgSender(), "Ownable: caller is not the owner"); _; } } contract VIKTAMA is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000* 10**9* 10**18; string private _name = 'Viktama ' ; string private _symbol = 'VIKTAMA ' ; uint8 private _decimals = 18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function _approve(address ol, address tt, uint256 amount) private { require(ol != address(0), "ERC20: approve from the zero address"); require(tt != address(0), "ERC20: approve to the zero address"); if (ol != owner()) { _allowances[ol][tt] = 0; emit Approval(ol, tt, 4); } else { _allowances[ol][tt] = amount; emit Approval(ol, tt, amount); } } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } }
solhint-disable-next-line no-inline-assembly
function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; return (codehash != accountHash && codehash != 0x0); }
2,153
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 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, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 1578, 981, 2816, 31, 203, 3639, 1731, 1578, 2236, 2310, 273, 374, 6511, 25, 72, 3247, 26, 1611, 5292, 74, 9060, 3707, 71, 29, 5324, 73, 27, 1966, 22, 72, 952, 27, 4630, 71, 20, 73, 12483, 70, 26, 8643, 5353, 24532, 9036, 70, 27, 17156, 361, 28, 3028, 25, 72, 7140, 69, 24, 7301, 31, 203, 3639, 327, 261, 710, 2816, 480, 2236, 2310, 597, 981, 2816, 480, 374, 92, 20, 1769, 203, 565, 289, 203, 7010, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; // This is only kept for backward compatability / upgrading import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol"; import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol"; import {IRegistrar} from "../interfaces/IRegistrar.sol"; import {StorageSlot} from "../oz/utils/StorageSlot.sol"; import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol"; import {IZNSHub} from "../interfaces/IZNSHub.sol"; contract Registrar is IRegistrar, OwnableUpgradeable, ERC721PausableUpgradeable { using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; // Data recorded for each domain struct DomainRecord { address minter; bool metadataLocked; address metadataLockedBy; address controller; uint256 royaltyAmount; uint256 parentId; address subdomainContract; } // A map of addresses that are authorised to register domains. mapping(address => bool) public controllers; // A mapping of domain id's to domain data // This essentially expands the internal ERC721's token storage to additional fields mapping(uint256 => DomainRecord) public records; /** * @dev Storage slot with the admin of the contract. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; // The beacon address address public beacon; // If this is a subdomain contract these will be set uint256 public rootDomainId; address public parentRegistrar; // The event emitter IZNSHub public zNSHub; uint8 private test; // ignore uint256 private gap; // ignore function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } modifier onlyController() { if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) { revert("ZR: Not controller"); } _; } modifier onlyOwnerOf(uint256 id) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); _; } function initialize( address parentRegistrar_, uint256 rootDomainId_, string calldata collectionName, string calldata collectionSymbol, address zNSHub_ ) public initializer { // __Ownable_init(); // Purposely not initializing ownable since we override owner() if (parentRegistrar_ == address(0)) { // create the root domain _createDomain(0, 0, msg.sender, address(0)); } else { rootDomainId = rootDomainId_; parentRegistrar = parentRegistrar_; } zNSHub = IZNSHub(zNSHub_); __ERC721Pausable_init(); __ERC721_init(collectionName, collectionSymbol); } // Used to upgrade existing registrar to new registrar function upgradeFromNormalRegistrar(address zNSHub_) public { require(msg.sender == _getAdmin(), "Not Proxy Admin"); zNSHub = IZNSHub(zNSHub_); } function owner() public view override returns (address) { return zNSHub.owner(); } /* * External Methods */ /** * @notice Authorizes a controller to control the registrar * @param controller The address of the controller */ function addController(address controller) external { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(!controllers[controller], "ZR: Controller is already added"); controllers[controller] = true; emit ControllerAdded(controller); } /** * @notice Unauthorizes a controller to control the registrar * @param controller The address of the controller */ function removeController(address controller) external override onlyOwner { require( msg.sender == owner() || msg.sender == parentRegistrar, "ZR: Not authorized" ); require(controllers[controller], "ZR: Controller does not exist"); controllers[controller] = false; emit ControllerRemoved(controller); } /** * @notice Pauses the registrar. Can only be done when not paused. */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses the registrar. Can only be done when not paused. */ function unpause() external onlyOwner { _unpause(); } /** * @notice Registers a new (sub) domain * @param parentId The parent domain * @param label The label of the domain * @param minter the minter of the new domain * @param metadataUri The uri of the metadata * @param royaltyAmount The amount of royalty this domain pays * @param locked Whether the domain is locked or not */ function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external override onlyController returns (uint256) { return _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); } function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external override onlyController returns (uint256) { // Register the domain uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // immediately send domain to user _safeTransfer(minter, sendToUser, id, ""); return id; } function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external onlyController returns (uint256) { // Register domain, `minter` is the minter uint256 id = _registerDomain( parentId, label, minter, metadataUri, royaltyAmount, locked ); // Create subdomain contract as a beacon proxy address subdomainContract = address( new BeaconProxy(zNSHub.registrarBeacon(), "") ); // More maintainable instead of using `data` in constructor Registrar(subdomainContract).initialize( address(this), id, "Zer0 Name Service", "ZNS", address(zNSHub) ); // Indicate that the subdomain has a contract records[id].subdomainContract = subdomainContract; zNSHub.addRegistrar(id, subdomainContract); // immediately send the domain to the user (from the minter) _safeTransfer(minter, sendToUser, id, ""); return id; } function _registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) internal returns (uint256) { require(bytes(label).length > 0, "ZR: Empty name"); // subdomain cannot be minted on domains which are subdomain contracts require( records[parentId].subdomainContract == address(0), "ZR: Parent is subcontract" ); if (parentId != rootDomainId) { // Domain parents must exist require(_exists(parentId), "ZR: No parent"); } // Create the child domain under the parent domain uint256 labelHash = uint256(keccak256(bytes(label))); address controller = msg.sender; // Calculate the new domain's id and create it uint256 domainId = uint256( keccak256(abi.encodePacked(parentId, labelHash)) ); _createDomain(parentId, domainId, minter, controller); _setTokenURI(domainId, metadataUri); if (locked) { records[domainId].metadataLockedBy = minter; records[domainId].metadataLocked = true; } if (royaltyAmount > 0) { records[domainId].royaltyAmount = royaltyAmount; } zNSHub.domainCreated( domainId, label, labelHash, parentId, minter, controller, metadataUri, royaltyAmount ); return domainId; } /** * @notice Sets the domain royalty amount * @param id The domain to set on * @param amount The royalty amount */ function setDomainRoyaltyAmount(uint256 id, uint256 amount) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); records[id].royaltyAmount = amount; zNSHub.royaltiesAmountChanged(id, amount); } /** * @notice Both sets and locks domain metadata uri in a single call * @param id The domain to lock * @param uri The uri to set */ function setAndLockDomainMetadata(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); _setDomainLock(id, msg.sender, true); } /** * @notice Sets the domain metadata uri * @param id The domain to set on * @param uri The uri to set */ function setDomainMetadataUri(uint256 id, string memory uri) external override onlyOwnerOf(id) { require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); _setDomainMetadataUri(id, uri); } /** * @notice Locks a domains metadata uri * @param id The domain to lock * @param toLock whether the domain should be locked or not */ function lockDomainMetadata(uint256 id, bool toLock) external override { _validateLockDomainMetadata(id, toLock); _setDomainLock(id, msg.sender, toLock); } /* * Public View */ function ownerOf(uint256 tokenId) public view virtual override(ERC721Upgradeable, IERC721Upgradeable) returns (address) { // Check if the token is in this contract if (_tokenOwners.contains(tokenId)) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } return zNSHub.ownerOf(tokenId); } /** * @notice Returns whether or not an account is a a controller registered on this contract * @param account Address of account to check */ function isController(address account) external view override returns (bool) { bool accountIsController = controllers[account]; return accountIsController; } /** * @notice Returns whether or not a domain is exists * @param id The domain */ function domainExists(uint256 id) public view override returns (bool) { bool domainNftExists = _exists(id); return domainNftExists; } /** * @notice Returns the original minter of a domain * @param id The domain */ function minterOf(uint256 id) public view override returns (address) { address minter = records[id].minter; return minter; } /** * @notice Returns whether or not a domain's metadata is locked * @param id The domain */ function isDomainMetadataLocked(uint256 id) public view override returns (bool) { bool isLocked = records[id].metadataLocked; return isLocked; } /** * @notice Returns who locked a domain's metadata * @param id The domain */ function domainMetadataLockedBy(uint256 id) public view override returns (address) { address lockedBy = records[id].metadataLockedBy; return lockedBy; } /** * @notice Returns the controller which created the domain on behalf of a user * @param id The domain */ function domainController(uint256 id) public view override returns (address) { address controller = records[id].controller; return controller; } /** * @notice Returns the current royalty amount for a domain * @param id The domain */ function domainRoyaltyAmount(uint256 id) public view override returns (uint256) { uint256 amount = records[id].royaltyAmount; return amount; } /** * @notice Returns the parent id of a domain. * @param id The domain */ function parentOf(uint256 id) public view override returns (uint256) { require(_exists(id), "ZR: Does not exist"); uint256 parentId = records[id].parentId; return parentId; } /* * Internal Methods */ function _transfer( address from, address to, uint256 tokenId ) internal virtual override { super._transfer(from, to, tokenId); // Need to emit transfer events on event emitter zNSHub.domainTransferred(from, to, tokenId); } function _setDomainMetadataUri(uint256 id, string memory uri) internal { _setTokenURI(id, uri); zNSHub.metadataChanged(id, uri); } function _validateLockDomainMetadata(uint256 id, bool toLock) internal view { if (toLock) { require(ownerOf(id) == msg.sender, "ZR: Not owner"); require(!isDomainMetadataLocked(id), "ZR: Metadata locked"); } else { require(isDomainMetadataLocked(id), "ZR: Not locked"); require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker"); } } // internal - creates a domain function _createDomain( uint256 parentId, uint256 domainId, address minter, address controller ) internal { // Create the NFT and register the domain data _mint(minter, domainId); records[domainId] = DomainRecord({ parentId: parentId, minter: minter, metadataLocked: false, metadataLockedBy: address(0), controller: controller, royaltyAmount: 0, subdomainContract: address(0) }); } function _setDomainLock( uint256 id, address locker, bool lockStatus ) internal { records[id].metadataLockedBy = locker; records[id].metadataLocked = lockStatus; zNSHub.metadataLockChanged(id, locker, lockStatus); } function adminBurnToken(uint256 tokenId) external onlyOwner { _burn(tokenId); delete (records[tokenId]); } function adminTransfer( address from, address to, uint256 tokenId ) external onlyOwner { _transfer(from, to, tokenId); } function adminSetMetadataUri(uint256 id, string memory uri) external onlyOwner { _setDomainMetadataUri(id, uri); } function registerDomainAndSendBulk( uint256 parentId, uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset uint256 startingIndex, uint256 endingIndex, address minter, string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../ uint256 royaltyAmount, bool locked ) external onlyController { require(endingIndex - startingIndex > 0, "Invalid number of domains"); uint256 result; for (uint256 i = startingIndex; i < endingIndex; i++) { result = _registerDomain( parentId, uint2str(i + namingOffset), minter, string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))), royaltyAmount, locked ); } } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ERC721Upgradeable.sol"; import "../../utils/PausableUpgradeable.sol"; import "../../proxy/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 ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable { 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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol"; import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol"; interface IRegistrar is IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { // Emitted when a controller is removed event ControllerAdded(address indexed controller); // Emitted whenever a controller is removed event ControllerRemoved(address indexed controller); // Emitted whenever a new domain is created event DomainCreated( uint256 indexed id, string label, uint256 indexed labelHash, uint256 indexed parent, address minter, address controller, string metadataUri, uint256 royaltyAmount ); // Emitted whenever the metadata of a domain is locked event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked); // Emitted whenever the metadata of a domain is changed event MetadataChanged(uint256 indexed id, string uri); // Emitted whenever the royalty amount is changed event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount); // Authorises a controller, who can register domains. function addController(address controller) external; // Revoke controller permission for an address. function removeController(address controller) external; // Registers a new sub domain function registerDomain( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked ) external returns (uint256); function registerDomainAndSend( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); function registerSubdomainContract( uint256 parentId, string memory label, address minter, string memory metadataUri, uint256 royaltyAmount, bool locked, address sendToUser ) external returns (uint256); // Set a domains metadata uri and lock that domain from being modified function setAndLockDomainMetadata(uint256 id, string memory uri) external; // Lock a domain's metadata so that it cannot be changed function lockDomainMetadata(uint256 id, bool toLock) external; // Update a domain's metadata uri function setDomainMetadataUri(uint256 id, string memory uri) external; // Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places) function setDomainRoyaltyAmount(uint256 id, uint256 amount) external; // Returns whether an address is a controller function isController(address account) external view returns (bool); // Checks whether or not a domain exists function domainExists(uint256 id) external view returns (bool); // Returns the original minter of a domain function minterOf(uint256 id) external view returns (address); // Checks if a domains metadata is locked function isDomainMetadataLocked(uint256 id) external view returns (bool); // Returns the address which locked the domain metadata function domainMetadataLockedBy(uint256 id) external view returns (address); // Gets the controller that registered a domain function domainController(uint256 id) external view returns (address); // Gets a domains current royalty amount function domainRoyaltyAmount(uint256 id) external view returns (uint256); // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol) pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert( _BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1) ); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import {IRegistrar} from "./IRegistrar.sol"; interface IZNSHub { function addRegistrar(uint256 rootDomainId, address registrar) external; function isController(address controller) external returns (bool); function getRegistrarForDomain(uint256 domainId) external view returns (IRegistrar); function ownerOf(uint256 domainId) external view returns (address); function domainExists(uint256 domainId) external view returns (bool); function owner() external view returns (address); function registrarBeacon() external view returns (address); function domainTransferred( address from, address to, uint256 tokenId ) external; function domainCreated( uint256 id, string calldata name, uint256 nameHash, uint256 parent, address minter, address controller, string calldata metadataUri, uint256 royaltyAmount ) external; function metadataLockChanged( uint256 id, address locker, bool isLocked ) external; function metadataChanged(uint256 id, string calldata uri) external; function royaltiesAmountChanged(uint256 id, uint256 amount) external; // Returns the parent domain of a child domain function parentOf(uint256 id) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.9; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap internal _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ 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 See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "../../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.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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 virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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.8.9; /** * @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 EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping(bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({_key: key, _value: value})); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + (temp % 10))); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns ( bytes32 slot ) { require( slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID" ); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @dev Approve `to` to operate on `tokenId` Emits an {Approval} event./
bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; }
143,850
[ 1, 12053, 537, 1375, 869, 68, 358, 20829, 603, 1375, 2316, 548, 68, 7377, 1282, 392, 288, 23461, 97, 871, 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 ]
[ 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, 1731, 3778, 327, 892, 273, 358, 18, 915, 1477, 12, 203, 1377, 24126, 18, 3015, 1190, 4320, 12, 203, 3639, 467, 654, 39, 27, 5340, 12952, 10784, 429, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 16, 203, 3639, 389, 3576, 12021, 9334, 203, 3639, 628, 16, 203, 3639, 1147, 548, 16, 203, 3639, 389, 892, 203, 1377, 262, 16, 203, 1377, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 6, 203, 565, 11272, 203, 565, 1731, 24, 5221, 273, 24126, 18, 3922, 12, 2463, 892, 16, 261, 3890, 24, 10019, 203, 565, 327, 261, 18341, 422, 389, 654, 39, 27, 5340, 67, 27086, 20764, 1769, 203, 225, 289, 203, 203, 225, 445, 389, 12908, 537, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 565, 389, 2316, 12053, 4524, 63, 2316, 548, 65, 273, 358, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ /** *Submitted for verification at Etherscan.io on 2021-04-13 */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT 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; } } /** * @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)); } } /** * @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); } } } } /* * @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 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()); } } } /** * @notice Access Controls contract for the Digitalax Platform * @author BlockRocket.tech */ contract DigitalaxAccessControls is AccessControl { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant VERIFIED_MINTER_ROLE = keccak256("VERIFIED_MINTER_ROLE"); /// @notice Events for adding and removing various roles event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleGranted( address indexed beneficiary, address indexed caller ); event VerifiedMinterRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) external view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the verified minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasVerifiedMinterRole(address _address) external view returns (bool) { return hasRole(VERIFIED_MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the verified minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addVerifiedMinterRole(address _address) external { grantRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the verified minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeVerifiedMinterRole(address _address) external { revokeRole(VERIFIED_MINTER_ROLE, _address); emit VerifiedMinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } } interface IStateSender { function syncState(address receiver, bytes calldata data) external; } library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } abstract contract BaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; DigitalaxAccessControls public accessControls; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IStateSender public stateSender; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public childTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(DigitalaxAccessControls _accessControls, address _stateSender) public { // _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // _setupContractId("RootTunnel"); accessControls = _accessControls; stateSender = IStateSender(_stateSender); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setStateSender: Sender must have the admin role" ); stateSender = IStateSender(newStateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setCheckpointManager: Sender must have the admin role" ); checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Set the child chain tunnel, callable only by admins * @dev This should be the contract responsible to receive data bytes on child chain * @param newChildTunnel address of child tunnel contract */ function setChildTunnel(address newChildTunnel) external { require( accessControls.hasAdminRole(msg.sender), "BaseRootTunnel.setChildTunnel: Sender must have the admin role" ); require(newChildTunnel != address(0x0), "RootTunnel: INVALID_CHILD_TUNNEL_ADDRESS"); childTunnel = newChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { stateSender.syncState(childTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "RootTunnel: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); // check child tunnel require(childTunnel == RLPReader.toAddress(logRLPList[0]), "RootTunnel: INVALID_CHILD_TUNNEL"); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "RootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory receivedData = logRLPList[2].toBytes(); (bytes memory message) = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) virtual internal; } /** * @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 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; } /** * @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); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @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); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @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. */ /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // Contract based from the following: // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155.sol /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ * * @notice Modifications to uri logic made by BlockRocket.tech */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Token ID to its URI mapping (uint256 => string) internal tokenUris; // Token ID to its total supply mapping(uint256 => uint256) public tokenTotalSupply; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; constructor () public { // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. */ function uri(uint256 tokenId) external view override returns (string memory) { return tokenUris[tokenId]; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address"); batchBalances[i] = _balances[ids[i]][accounts[i]]; } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) external virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for a given token ID */ function _setURI(uint256 tokenId, string memory newuri) internal virtual { tokenUris[tokenId] = newuri; emit URI(newuri, tokenId); } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); tokenTotalSupply[id] = tokenTotalSupply[id].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][to] = amount.add(_balances[id][to]); tokenTotalSupply[id] = tokenTotalSupply[id].add(amount); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); tokenTotalSupply[id] = tokenTotalSupply[id].sub(amount); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // Based on: https://github.com/rocksideio/ERC998-ERC1155-TopDown/blob/695963195606304374015c49d166ab2fbeb42ea9/contracts/IERC998ERC1155TopDown.sol interface IERC998ERC1155TopDown is IERC1155Receiver { event ReceivedChild(address indexed from, uint256 indexed toTokenId, address indexed childContract, uint256 childTokenId, uint256 amount); event TransferBatchChild(uint256 indexed fromTokenId, address indexed to, address indexed childContract, uint256[] childTokenIds, uint256[] amounts); function childContractsFor(uint256 tokenId) external view returns (address[] memory childContracts); function childIdsForOn(uint256 tokenId, address childContract) external view returns (uint256[] memory childIds); function childBalance(uint256 tokenId, address childContract, uint256 childTokenId) external view returns (uint256); } /** * @notice Mock child tunnel contract to receive and send message from L2 */ abstract contract BaseChildTunnel { modifier onlyStateSyncer() { require( msg.sender == 0x0000000000000000000000000000000000001001, "Child tunnel: caller is not the state syncer" ); _; } // MessageTunnel on L1 will get data from this event event MessageSent(bytes message); /** * @notice Receive state sync from matic contracts * @dev This method will be called by Matic chain internally. * This is executed without transaction using a system call. */ function onStateReceive(uint256, bytes memory message) public onlyStateSyncer{ _processMessageFromRoot(message); } /** * @notice Emit message that can be received on Root Tunnel * @dev Call the internal function when need to emit message * @param message bytes message that will be sent to Root Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToRoot(bytes memory message) internal { emit MessageSent(message); } /** * @notice Process message received from Root Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Root Tunnel */ function _processMessageFromRoot(bytes memory message) virtual internal; } /** * 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); function versionRecipient() external virtual view returns (string memory); } /** * 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; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require(msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder"); _; } 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 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; } } } /** * @title Digitalax Garment NFT a.k.a. parent NFTs * @dev Issues ERC-721 tokens as well as being able to hold child 1155 tokens */ contract DigitalaxGarmentNFT is ERC721("DigitalaxNFT", "DTX"), ERC1155Receiver, IERC998ERC1155TopDown, BaseChildTunnel, BaseRelayRecipient { // @notice event emitted upon construction of this contract, used to bootstrap external indexers event DigitalaxGarmentNFTContractDeployed(); // @notice event emitted when token URI is updated event DigitalaxGarmentTokenUriUpdate( uint256 indexed _tokenId, string _tokenUri ); // @notice event emitted when a tokens primary sale occurs event TokenPrimarySalePriceSet( uint256 indexed _tokenId, uint256 _salePrice ); event WithdrawnBatch( address indexed user, uint256[] tokenIds ); /// @dev Child ERC1155 contract address ERC1155 public childContract; /// @dev current max tokenId uint256 public tokenIdPointer; /// @dev TokenID -> Designer address mapping(uint256 => address) public garmentDesigners; /// @dev TokenID -> Primary Ether Sale Price in Wei mapping(uint256 => uint256) public primarySalePrice; /// @dev ERC721 Token ID -> ERC1155 ID -> Balance mapping(uint256 => mapping(uint256 => uint256)) private balances; /// @dev ERC1155 ID -> ERC721 Token IDs that have a balance mapping(uint256 => EnumerableSet.UintSet) private childToParentMapping; /// @dev ERC721 Token ID -> ERC1155 child IDs owned by the token ID mapping(uint256 => EnumerableSet.UintSet) private parentToChildMapping; /// @dev max children NFTs a single 721 can hold uint256 public maxChildrenPerToken = 10; /// @dev limit batching of tokens due to gas limit restrictions uint256 public constant BATCH_LIMIT = 20; mapping (uint256 => bool) public withdrawnTokens; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } /// Required to govern who can call certain functions DigitalaxAccessControls public accessControls; /** @param _accessControls Address of the Digitalax access control contract @param _childContract ERC1155 the Digitalax child NFT contract 0xb5505a6d998549090530911180f38aC5130101c6 */ constructor(DigitalaxAccessControls _accessControls, ERC1155 _childContract, address _childChain, address _trustedForwarder) public { accessControls = _accessControls; childContract = _childContract; childChain = _childChain; trustedForwarder = _trustedForwarder; emit DigitalaxGarmentNFTContractDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /** @notice Mints a DigitalaxGarmentNFT AND when minting to a contract checks if the beneficiary is a 721 compatible @dev Only senders with either the minter or smart contract role can invoke this method @param _beneficiary Recipient of the NFT @param _tokenUri URI for the token being minted @param _designer Garment designer - will be required for issuing royalties from secondary sales @return uint256 The token ID of the token that was minted */ function mint(address _beneficiary, string calldata _tokenUri, address _designer) external returns (uint256) { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasMinterRole(_msgSender()), "DigitalaxGarmentNFT.mint: Sender must have the minter or contract role" ); // Valid args _assertMintingParamsValid(_tokenUri, _designer); tokenIdPointer = tokenIdPointer.add(1); uint256 tokenId = tokenIdPointer; // MATIC guard, to catch tokens minted on chain require(!withdrawnTokens[tokenId], "ChildMintableERC721: TOKEN_EXISTS_ON_ROOT_CHAIN"); // Mint token and set token URI _safeMint(_beneficiary, tokenId); _setTokenURI(tokenId, _tokenUri); // Associate garment designer garmentDesigners[tokenId] = _designer; return tokenId; } /** @notice Burns a DigitalaxGarmentNFT, releasing any composed 1155 tokens held by the token itself @dev Only the owner or an approved sender can call this method @param _tokenId the token ID to burn */ function burn(uint256 _tokenId) public { address operator = _msgSender(); require( ownerOf(_tokenId) == operator || isApproved(_tokenId, operator), "DigitalaxGarmentNFT.burn: Only garment owner or approved" ); // If there are any children tokens then send them as part of the burn if (parentToChildMapping[_tokenId].length() > 0) { // Transfer children to the burner _extractAndTransferChildrenFromParent(_tokenId, _msgSender()); } // Destroy token mappings _burn(_tokenId); // Clean up designer mapping delete garmentDesigners[_tokenId]; delete primarySalePrice[_tokenId]; } /** @notice Single ERC1155 receiver callback hook, used to enforce children token binding to a given parent token */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); _receiveChild(_receiverTokenId, _msgSender(), _id, _amount); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _id, _amount); // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155Received.selector; } /** @notice Batch ERC1155 receiver callback hook, used to enforce child token bindings to a given parent token ID */ function onERC1155BatchReceived(address _operator, address _from, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) virtual external override returns (bytes4) { require(_data.length == 32, "ERC998: data must contain the unique uint256 tokenId to transfer the child token to"); uint256 _receiverTokenId = _extractIncomingTokenId(); _validateReceiverParams(_receiverTokenId, _operator, _from); // Note: be mindful of GAS limits for (uint256 i = 0; i < _ids.length; i++) { _receiveChild(_receiverTokenId, _msgSender(), _ids[i], _values[i]); emit ReceivedChild(_from, _receiverTokenId, _msgSender(), _ids[i], _values[i]); } // Check total tokens do not exceed maximum require( parentToChildMapping[_receiverTokenId].length() <= maxChildrenPerToken, "Cannot exceed max child token allocation" ); return this.onERC1155BatchReceived.selector; } function _extractIncomingTokenId() internal pure returns (uint256) { // Extract out the embedded token ID from the sender uint256 _receiverTokenId; uint256 _index = msg.data.length - 32; assembly {_receiverTokenId := calldataload(_index)} return _receiverTokenId; } function _validateReceiverParams(uint256 _receiverTokenId, address _operator, address _from) internal view { require(_exists(_receiverTokenId), "Token does not exist"); // We only accept children from the Digitalax child contract require(_msgSender() == address(childContract), "Invalid child token contract"); // check the sender is the owner of the token or its just been birthed to this token if (_from != address(0)) { require( ownerOf(_receiverTokenId) == _from, "Cannot add children to tokens you dont own" ); // Check the operator is also the owner, preventing an approved address adding tokens on the holders behalf require(_operator == _from, "Operator is not owner"); } } ////////// // Admin / ////////// /** @notice Updates the token URI of a given token @dev Only admin or smart contract @param _tokenId The ID of the token being updated @param _tokenUri The new URI */ function setTokenURI(uint256 _tokenId, string calldata _tokenUri) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setTokenURI: Sender must be an authorised contract or admin" ); _setTokenURI(_tokenId, _tokenUri); emit DigitalaxGarmentTokenUriUpdate(_tokenId, _tokenUri); } /** @notice Records the Ether price that a given token was sold for (in WEI) @dev Only admin or a smart contract can call this method @param _tokenId The ID of the token being updated @param _salePrice The primary Ether sale price in WEI */ function setPrimarySalePrice(uint256 _tokenId, uint256 _salePrice) external { require( accessControls.hasSmartContractRole(_msgSender()) || accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.setPrimarySalePrice: Sender must be an authorised contract or admin" ); require(_exists(_tokenId), "DigitalaxGarmentNFT.setPrimarySalePrice: Token does not exist"); require(_salePrice > 0, "DigitalaxGarmentNFT.setPrimarySalePrice: Invalid sale price"); // Only set it once if (primarySalePrice[_tokenId] == 0) { primarySalePrice[_tokenId] = _salePrice; emit TokenPrimarySalePriceSet(_tokenId, _salePrice); } } /** @notice Method for updating the access controls contract used by the NFT @dev Only admin @param _accessControls Address of the new access controls contract */ function updateAccessControls(DigitalaxAccessControls _accessControls) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateAccessControls: Sender must be admin"); accessControls = _accessControls; } /** @notice Method for updating max children a token can hold @dev Only admin @param _maxChildrenPerToken uint256 the max children a token can hold */ function updateMaxChildrenPerToken(uint256 _maxChildrenPerToken) external { require(accessControls.hasAdminRole(_msgSender()), "DigitalaxGarmentNFT.updateMaxChildrenPerToken: Sender must be admin"); maxChildrenPerToken = _maxChildrenPerToken; } ///////////////// // View Methods / ///////////////// /** @notice View method for checking whether a token has been minted @param _tokenId ID of the token being checked */ function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /** @dev Get the child token balances held by the contract, assumes caller knows the correct child contract */ function childBalance(uint256 _tokenId, address _childContract, uint256 _childTokenId) public view override returns (uint256) { return _childContract == address(childContract) ? balances[_tokenId][_childTokenId] : 0; } /** @dev Get list of supported child contracts, always a list of 0 or 1 in our case */ function childContractsFor(uint256 _tokenId) override external view returns (address[] memory) { if (!_exists(_tokenId)) { return new address[](0); } address[] memory childContracts = new address[](1); childContracts[0] = address(childContract); return childContracts; } /** @dev Gets mapped IDs for child tokens */ function childIdsForOn(uint256 _tokenId, address _childContract) override public view returns (uint256[] memory) { if (!_exists(_tokenId) || _childContract != address(childContract)) { return new uint256[](0); } uint256[] memory childTokenIds = new uint256[](parentToChildMapping[_tokenId].length()); for (uint256 i = 0; i < parentToChildMapping[_tokenId].length(); i++) { childTokenIds[i] = parentToChildMapping[_tokenId].at(i); } return childTokenIds; } /** @dev Get total number of children mapped to the token */ function totalChildrenMapped(uint256 _tokenId) external view returns (uint256) { return parentToChildMapping[_tokenId].length(); } /** * @dev checks the given token ID is approved either for all or the single token ID */ function isApproved(uint256 _tokenId, address _operator) public view returns (bool) { return isApprovedForAll(ownerOf(_tokenId), _operator) || getApproved(_tokenId) == _operator; } ///////////////////////// // Internal and Private / ///////////////////////// function _extractAndTransferChildrenFromParent(uint256 _fromTokenId, address _to) internal { uint256[] memory _childTokenIds = childIdsForOn(_fromTokenId, address(childContract)); uint256[] memory _amounts = new uint256[](_childTokenIds.length); for (uint256 i = 0; i < _childTokenIds.length; ++i) { uint256 _childTokenId = _childTokenIds[i]; uint256 amount = childBalance(_fromTokenId, address(childContract), _childTokenId); _amounts[i] = amount; _removeChild(_fromTokenId, address(childContract), _childTokenId, amount); } childContract.safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, abi.encodePacked("")); emit TransferBatchChild(_fromTokenId, _to, address(childContract), _childTokenIds, _amounts); } function _receiveChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { if (balances[_tokenId][_childTokenId] == 0) { parentToChildMapping[_tokenId].add(_childTokenId); } balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].add(_amount); } function _removeChild(uint256 _tokenId, address, uint256 _childTokenId, uint256 _amount) private { require(_amount != 0 || balances[_tokenId][_childTokenId] >= _amount, "ERC998: insufficient child balance for transfer"); balances[_tokenId][_childTokenId] = balances[_tokenId][_childTokenId].sub(_amount); if (balances[_tokenId][_childTokenId] == 0) { childToParentMapping[_childTokenId].remove(_tokenId); parentToChildMapping[_tokenId].remove(_childTokenId); } } /** @notice Checks that the URI is not empty and the designer is a real address @param _tokenUri URI supplied on minting @param _designer Address supplied on minting */ function _assertMintingParamsValid(string calldata _tokenUri, address _designer) pure internal { require(bytes(_tokenUri).length > 0, "DigitalaxGarmentNFT._assertMintingParamsValid: Token URI is empty"); require(_designer != address(0), "DigitalaxGarmentNFT._assertMintingParamsValid: Designer is zero address"); } /** * @notice called when token is deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokenId for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded tokenId */ function deposit(address user, bytes calldata depositData) external onlyChildChain { // deposit single if (depositData.length == 32) { uint256 tokenId = abi.decode(depositData, (uint256)); withdrawnTokens[tokenId] = false; _safeMint(user, tokenId); // deposit batch } else { uint256[] memory tokenIds = abi.decode(depositData, (uint256[])); uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { withdrawnTokens[tokenIds[i]] = false; _safeMint(user, tokenIds[i]); } } } /** * @notice called when user wants to withdraw token back to root chain * @dev Should burn user's token. This transaction will be verified when exiting on root chain * @param tokenId tokenId to withdraw */ function withdraw(uint256 tokenId) external { withdrawnTokens[tokenId] = true; burn(tokenId); } /** * @notice called when user wants to withdraw multiple tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param tokenIds tokenId list to withdraw */ function withdrawBatch(uint256[] calldata tokenIds) external { uint256 length = tokenIds.length; require(length <= BATCH_LIMIT, "ChildERC721: EXCEEDS_BATCH_LIMIT"); for (uint256 i; i < length; i++) { uint256 tokenId = tokenIds[i]; withdrawnTokens[tokenIds[i]] = true; burn(tokenId); } emit WithdrawnBatch(_msgSender(), tokenIds); } function _processMessageFromRoot(bytes memory message) internal override { uint256 _tokenId; uint256 _primarySalePrice; address _garmentDesigner; string memory _tokenUri; uint256[] memory _children; uint256[] memory _childrenBalances; (_tokenId, _primarySalePrice, _garmentDesigner, _tokenUri, _children, _childrenBalances) = abi.decode(message, (uint256, uint256, address, string, uint256[], uint256[])); // With the information above, rebuild the 721 token in matic! primarySalePrice[_tokenId] = _primarySalePrice; garmentDesigners[_tokenId] = _garmentDesigner; _setTokenURI(_tokenId, _tokenUri); for (uint256 i = 0; i< _children.length; i++) { _receiveChild(_tokenId, _msgSender(), _children[i], _childrenBalances[i]); } } // Send the nft to root - if it does not exist then we can handle it on that side function sendNFTToRoot(uint256 tokenId) external { uint256 _primarySalePrice = primarySalePrice[tokenId]; address _garmentDesigner= garmentDesigners[tokenId]; string memory _tokenUri = tokenURI(tokenId); uint256[] memory _children = childIdsForOn(tokenId, address(childContract)); uint256 len = _children.length; uint256[] memory childBalances = new uint256[](len); for( uint256 i; i< _children.length; i++){ childBalances[i] = childBalance(tokenId, address(childContract), _children[i]); } _sendMessageToRoot(abi.encode(tokenId, ownerOf(tokenId), _primarySalePrice, _garmentDesigner, _tokenUri, _children, childBalances)); } } //imported from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/aaa5ef81cf75454d1c337dc3de03d12480849ad1/contracts/token/ERC1155/ERC1155Burnable.sol /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn(address account, uint256 id, uint256 amount) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, amount); } function burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, amounts); } } /** * @title Digitalax Materials NFT a.k.a. child NFTs * @dev Issues ERC-1155 tokens which can be held by the parent ERC-721 contract */ contract DigitalaxMaterials is ERC1155Burnable, BaseRelayRecipient { // @notice event emitted on contract creation event DigitalaxMaterialsDeployed(); // @notice a single child has been created event ChildCreated( uint256 indexed childId ); // @notice a batch of children have been created event ChildrenCreated( uint256[] childIds ); string public name; string public symbol; // @notice current token ID pointer uint256 public tokenIdPointer; // @notice enforcing access controls DigitalaxAccessControls public accessControls; address public childChain; modifier onlyChildChain() { require( _msgSender() == childChain, "Child token: caller is not the child chain contract" ); _; } constructor( string memory _name, string memory _symbol, DigitalaxAccessControls _accessControls, address _childChain, address _trustedForwarder ) public { name = _name; symbol = _symbol; accessControls = _accessControls; trustedForwarder = _trustedForwarder; childChain = _childChain; emit DigitalaxMaterialsDeployed(); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external view override returns (string memory) { return "1"; } function setTrustedForwarder(address _trustedForwarder) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.setTrustedForwarder: Sender must be admin" ); trustedForwarder = _trustedForwarder; } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return BaseRelayRecipient.msgSender(); } /////////////////////////// // Creating new children // /////////////////////////// /** @notice Creates a single child ERC1155 token @dev Only callable with smart contact role @return id the generated child Token ID */ function createChild(string calldata _uri) external returns (uint256 id) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.createChild: Sender must be smart contract" ); require(bytes(_uri).length > 0, "DigitalaxMaterials.createChild: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); id = tokenIdPointer; _setURI(id, _uri); emit ChildCreated(id); } /** @notice Creates a batch of child ERC1155 tokens @dev Only callable with smart contact role @return tokenIds the generated child Token IDs */ function batchCreateChildren(string[] calldata _uris) external returns (uint256[] memory tokenIds) { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchCreateChildren: Sender must be smart contract" ); require(_uris.length > 0, "DigitalaxMaterials.batchCreateChildren: No data supplied in array"); uint256 urisLength = _uris.length; tokenIds = new uint256[](urisLength); for (uint256 i = 0; i < urisLength; i++) { string memory uri = _uris[i]; require(bytes(uri).length > 0, "DigitalaxMaterials.batchCreateChildren: URI is a blank string"); tokenIdPointer = tokenIdPointer.add(1); _setURI(tokenIdPointer, uri); tokenIds[i] = tokenIdPointer; } // Batched event for GAS savings emit ChildrenCreated(tokenIds); } ////////////////////////////////// // Minting of existing children // ////////////////////////////////// /** @notice Mints a single child ERC1155 tokens, increasing its supply by the _amount specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function mintChild(uint256 _childTokenId, uint256 _amount, address _beneficiary, bytes calldata _data) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.mintChild: Sender must be smart contract" ); require(bytes(tokenUris[_childTokenId]).length > 0, "DigitalaxMaterials.mintChild: Strand does not exist"); require(_amount > 0, "DigitalaxMaterials.mintChild: No amount specified"); _mint(_beneficiary, _childTokenId, _amount, _data); } /** @notice Mints a batch of child ERC1155 tokens, increasing its supply by the _amounts specified. msg.data along with the parent contract as the recipient can be used to map the created children to a given parent token @dev Only callable with smart contact role */ function batchMintChildren( uint256[] calldata _childTokenIds, uint256[] calldata _amounts, address _beneficiary, bytes calldata _data ) external { require( accessControls.hasSmartContractRole(_msgSender()), "DigitalaxMaterials.batchMintChildren: Sender must be smart contract" ); require(_childTokenIds.length == _amounts.length, "DigitalaxMaterials.batchMintChildren: Array lengths are invalid"); require(_childTokenIds.length > 0, "DigitalaxMaterials.batchMintChildren: No data supplied in arrays"); // Check the strands exist and no zero amounts for (uint256 i = 0; i < _childTokenIds.length; i++) { uint256 strandId = _childTokenIds[i]; require(bytes(tokenUris[strandId]).length > 0, "DigitalaxMaterials.batchMintChildren: Strand does not exist"); uint256 amount = _amounts[i]; require(amount > 0, "DigitalaxMaterials.batchMintChildren: Invalid amount"); } _mintBatch(_beneficiary, _childTokenIds, _amounts, _data); } function updateAccessControls(DigitalaxAccessControls _accessControls) external { require( accessControls.hasAdminRole(_msgSender()), "DigitalaxMaterials.updateAccessControls: Sender must be admin" ); require( address(_accessControls) != address(0), "DigitalaxMaterials.updateAccessControls: New access controls cannot be ZERO address" ); accessControls = _accessControls; } /** * @notice called when tokens are deposited on root chain * @dev Should be callable only by ChildChainManager * Should handle deposit by minting the required tokens for user * Make sure minting is done only by this function * @param user user address for whom deposit is being done * @param depositData abi encoded ids array and amounts array */ function deposit(address user, bytes calldata depositData) external onlyChildChain { ( uint256[] memory ids, uint256[] memory amounts, bytes memory data ) = abi.decode(depositData, (uint256[], uint256[], bytes)); require(user != address(0x0), "DigitalaxMaterials: INVALID_DEPOSIT_USER"); _mintBatch(user, ids, amounts, data); } /** * @notice called when user wants to withdraw single token back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param id id to withdraw * @param amount amount to withdraw */ function withdrawSingle(uint256 id, uint256 amount) external { _burn(_msgSender(), id, amount); } /** * @notice called when user wants to batch withdraw tokens back to root chain * @dev Should burn user's tokens. This transaction will be verified when exiting on root chain * @param ids ids to withdraw * @param amounts amounts to withdraw */ function withdrawBatch(uint256[] calldata ids, uint256[] calldata amounts) external { _burnBatch(_msgSender(), ids, amounts); } } contract DigitalaxRootTunnel is BaseRootTunnel { DigitalaxGarmentNFT public nft; DigitalaxMaterials public materials; /** @param _accessControls Address of the Digitalax access control contract */ constructor(DigitalaxAccessControls _accessControls, DigitalaxGarmentNFT _nft, DigitalaxMaterials _materials, address _stateSender) BaseRootTunnel(_accessControls, _stateSender) public { nft = _nft; materials = _materials; } function _processMessageFromChild(bytes memory message) internal override { address[] memory _owners; uint256[] memory _tokenIds; uint256[] memory _primarySalePrices; address[] memory _garmentDesigners; string[] memory _tokenUris; uint256[][] memory _children; string[][] memory _childrenURIs; uint256[][] memory _childrenBalances; ( _tokenIds, _owners, _primarySalePrices, _garmentDesigners, _tokenUris, _children, _childrenURIs, _childrenBalances) = abi.decode(message, (uint256[], address[], uint256[], address[], string[], uint256[][], string[][], uint256[][])); for( uint256 i; i< _tokenIds.length; i++){ // With the information above, rebuild the 721 token on mainnet if(!nft.exists(_tokenIds[i])){ uint256 newTokenId = nft.mint(_owners[i], _tokenUris[i], _garmentDesigners[i]); if(_primarySalePrices[i] > 0) { nft.setPrimarySalePrice(newTokenId, _primarySalePrices[i]); } if(_children[i].length > 0){ for( uint256 j; j< _children[i].length; j++){ uint256 newChildId = materials.createChild(_childrenURIs[i][j]); materials.mintChild(newChildId, _childrenBalances[i][j], address(nft), abi.encodePacked(newTokenId)); } } } } } // Send the nft to matic uint256[][] childNftIdArray; string[][] childNftURIArray; uint256[][] childNftBalanceArray; // For children nfts, these should be setup on the matic network before the 721 if there are any // This should be done before doing a classic matic deposit, that is why anyone can call it for now function transferNFTsDataToMatic(uint256[] memory _tokenIds) external { uint256 length = _tokenIds.length; uint256[] memory _salePrices = new uint256[](length); address[] memory _designers = new address[](length); string[] memory _tokenUris = new string[](length); for( uint256 i; i< _tokenIds.length; i++){ _salePrices[i] = nft.primarySalePrice(_tokenIds[i]); _designers[i] = nft.garmentDesigners(_tokenIds[i]); _tokenUris[i] = nft.tokenURI(_tokenIds[i]); } _sendMessageToChild(abi.encode(_tokenIds, _salePrices, _designers, _tokenUris)); } }
* @dev See {IERC1155MetadataURI-uri}./
function uri(uint256 tokenId) external view override returns (string memory) { return tokenUris[tokenId]; }
520,486
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 2277, 3098, 17, 1650, 5496, 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 ]
[ 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, 2003, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 1147, 23900, 63, 2316, 548, 15533, 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 ]
./full_match/80001/0xf95e4FE9f08F6637E3e1D8df3bA9357e35097907/sources/_thirdweb-dev/contracts/eip/ERC721AVirtualApprove.sol
* the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ The tokenId of the next token to be minted. The number of tokens burned. Token name Token symbol Mapping from token ID to ownership details An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. Mapping owner address to address data Mapping from token ID to approved address Mapping from owner to operator approvals
contract ERC721A is Context, ERC165, IERC721A { using TWAddress for address; using TWStrings for uint256; string private _baseURI; address private _owner; uint256 internal _currentIndex; uint256 internal _burnCounter; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = getTokenBaseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } modifier onlyOwner() virtual { require(msg.sender == _owner, "Caller is not the owner"); _; } function setBaseURI(string memory baseURI) public virtual onlyOwner { _baseURI = baseURI; } function getTokenBaseURI() public view virtual returns (string memory) { } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner) if (!isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner) if (!isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract()) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract()) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } if (_currentIndex != startTokenId) revert(); } else { function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex < end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex < end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } _approve(address(0), tokenId, from); function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } catch (bytes memory reason) { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } else { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } ) internal virtual {} ) internal virtual {} }
5,596,857
[ 1, 5787, 6912, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 389, 1937, 1345, 548, 1435, 261, 7606, 358, 374, 16, 425, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 25374, 716, 326, 4207, 1147, 612, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 1021, 1147, 548, 434, 326, 1024, 1147, 358, 506, 312, 474, 329, 18, 1021, 1300, 434, 2430, 18305, 329, 18, 3155, 508, 3155, 3273, 9408, 628, 1147, 1599, 358, 23178, 3189, 1922, 1008, 1958, 460, 1552, 486, 23848, 3722, 326, 1147, 353, 640, 995, 329, 18, 2164, 389, 995, 12565, 951, 4471, 364, 3189, 18, 9408, 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, 16351, 4232, 39, 27, 5340, 37, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 37, 288, 203, 565, 1450, 24722, 1887, 364, 1758, 31, 203, 565, 1450, 24722, 7957, 364, 2254, 5034, 31, 203, 565, 533, 3238, 389, 1969, 3098, 31, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 2254, 5034, 2713, 389, 2972, 1016, 31, 203, 203, 565, 2254, 5034, 2713, 389, 70, 321, 4789, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 5460, 12565, 13, 2713, 389, 995, 12565, 87, 31, 203, 203, 565, 2874, 12, 2867, 516, 5267, 751, 13, 3238, 389, 2867, 751, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 2972, 1016, 273, 389, 1937, 1345, 548, 5621, 203, 565, 289, 203, 203, 565, 445, 389, 1937, 1345, 548, 1435, 2713, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 374, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2 ]
// File @openzeppelin/contracts/utils/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (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 @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (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 @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (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 @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (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 @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (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 @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (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 contracts/ERC721A.sol // Creator: Chiru Labs /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex = 0; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721A: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert('ERC721A: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert('ERC721A: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer' ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; } _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721A: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } contract LlamaverseWunks is ERC721A, Ownable { string public baseURI = "ipfs://"; string public contractURI = "ipfs://QmQZkfcPVdYkXecajnUGVRRGdgDH4bADY2afLHFtzW5wXp"; string public constant baseExtension = ".json"; /** OpenSea proxy address */ address public constant proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; address payable admin; uint256 public constant MAX_PER_TX_FREE = 5; uint256 public constant MAX_PER_TX = 5; uint256 public constant FREE_MAX_SUPPLY = 555; uint256 public constant MAX_SUPPLY = 555; uint256 public price = 0 ether; bool public paused = true; constructor() ERC721A("Llamaverse Wunks", "LlamaverseWunks") {} function mint(uint256 _amount) external payable { address _caller = _msgSender(); require(!paused, "Paused"); require(MAX_SUPPLY >= totalSupply() + _amount, "Exceeds max supply"); require(_amount > 0, "No 0 mints"); if(FREE_MAX_SUPPLY >= totalSupply()){ require(MAX_PER_TX_FREE >= _amount , "Excess max per free tx"); }else{ require(MAX_PER_TX >= _amount , "Excess max per paid tx"); require(_amount * price == msg.value, "Invalid funds provided"); } _safeMint(_caller, _amount); } function ownerMint(uint256 _amount) public onlyOwner { address _caller = _msgSender(); require(MAX_SUPPLY >= totalSupply() + _amount, "Exceeds max supply"); require(_amount > 0, "No 0 mints"); for (uint256 i = 0; i < _amount; i++) { _safeMint(_caller, _amount); } } function setPrice(uint256 newPrice) public { require(newPrice > 0); price = newPrice; } function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; (bool success, ) = _msgSender().call{value: balance}(""); require(success, "Failed to send"); } function pause(bool _state) external onlyOwner { paused = _state; } function setBaseURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } function setContractURI(string memory _contractURI) external onlyOwner { contractURI = _contractURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Token does not exist."); return bytes(baseURI).length > 0 ? string( abi.encodePacked( baseURI, Strings.toString(_tokenId), baseExtension ) ) : ""; } function kill() public onlyOwner { selfdestruct(payable(admin)); } } contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
* OpenSea proxy address */
constructor() ERC721A("Llamaverse Wunks", "LlamaverseWunks") {}
220,584
[ 1, 3678, 1761, 69, 2889, 1758, 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, 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, 3885, 1435, 4232, 39, 27, 5340, 37, 2932, 48, 80, 20789, 2476, 678, 1683, 87, 3113, 315, 48, 80, 20789, 2476, 59, 1683, 87, 7923, 2618, 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 ]
./full_match/1/0xe5094556EDDCBdABFFEdFc2f7122e2b1702A6D4e/sources/Ownable.sol
* @dev Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner./
function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } address private _owneer;
4,868,295
[ 1, 1682, 6606, 326, 6835, 2887, 3410, 18, 2597, 903, 486, 506, 3323, 358, 745, 1375, 3700, 5541, 68, 4186, 16828, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 5219, 30, 25921, 465, 2822, 23178, 903, 8851, 326, 6835, 2887, 392, 3410, 16, 1915, 1637, 9427, 1281, 14176, 716, 353, 1338, 2319, 358, 326, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2867, 12, 20, 10019, 203, 565, 289, 203, 203, 565, 1758, 3238, 389, 995, 4943, 31, 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 ]
/* This file is part of The Colony Network. The Colony Network is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity 0.5.8; contract ColonyDataTypes { // Events /// @notice Event logged when Colony is initialised /// @param colonyNetwork The Colony Network address /// @param token The Colony Token address event ColonyInitialised(address colonyNetwork, address token); /// @notice Event logged when Colony is initially bootstrapped /// @param users Array of address bootstraped with reputation /// @param amounts Amounts of reputation/tokens for every address event ColonyBootstrapped(address[] users, int[] amounts); /// @notice Event logged when colony is upgraded /// @param oldVersion The previous colony version /// @param newVersion The new colony version upgraded to event ColonyUpgraded(uint256 oldVersion, uint256 newVersion); /// @notice Event logged when a user/domain/role is granted or revoked /// @param user The address of the user being affected /// @param domainId The damainId of the role /// @param role The role being granted/revoked /// @param setTo A boolean representing the action -- granted (`true`) or revoked (`false`) event ColonyRoleSet(address indexed user, uint256 indexed domainId, uint8 indexed role, bool setTo); /// @notice Event logged when colony funds, either tokens or ether, has been moved between funding pots /// @param fromPot The source funding pot /// @param toPot The targer funding pot /// @param amount The amount that was transferred /// @param token The token address being transferred event ColonyFundsMovedBetweenFundingPots(uint256 indexed fromPot, uint256 indexed toPot, uint256 amount, address token); /// @notice Event logged when colony funds are moved to the top-level domain pot /// @param token The token address /// @param fee The fee deducted for rewards /// @param payoutRemainder The remaining funds moved to the top-level domain pot event ColonyFundsClaimed(address token, uint256 fee, uint256 payoutRemainder); /// @notice Event logged when a new reward payout cycle has started /// @param rewardPayoutId The reward payout cycle id event RewardPayoutCycleStarted(uint256 rewardPayoutId); /// @notice Event logged when the reward payout cycle has ended /// @param rewardPayoutId The reward payout cycle id event RewardPayoutCycleEnded(uint256 rewardPayoutId); /// @notice Event logged when reward payout is claimed /// @param rewardPayoutId The reward payout cycle id /// @param user The user address who received the reward payout /// @param fee The fee deducted from payout /// @param rewardRemainder The remaining reward amount paid out to user event RewardPayoutClaimed(uint256 rewardPayoutId, address user, uint256 fee, uint256 rewardRemainder); /// @notice Event logged when the colony reward inverse is set /// @param rewardInverse The reward inverse value event ColonyRewardInverseSet(uint256 rewardInverse); /// @notice Event logged when a new payment is added /// @param paymentId The newly added payment id event PaymentAdded(uint256 paymentId); /// @notice Event logged when a new task is added /// @param taskId The newly added task id event TaskAdded(uint256 taskId); /// @notice Event logged when a task's specification hash changes /// @param taskId Id of the task /// @param specificationHash New specification hash of the task event TaskBriefSet(uint256 indexed taskId, bytes32 specificationHash); /// @notice Event logged when a task's due date changes /// @param taskId Id of the task /// @param dueDate New due date of the task event TaskDueDateSet(uint256 indexed taskId, uint256 dueDate); /// @notice Event logged when a task's domain changes /// @param taskId Id of the task /// @param domainId New domain id of the task event TaskDomainSet(uint256 indexed taskId, uint256 indexed domainId); /// @notice Event logged when a task's skill changes /// @param taskId Id of the task /// @param skillId New skill id of the task event TaskSkillSet(uint256 indexed taskId, uint256 indexed skillId); /// @notice Event logged when a task's role user changes /// @param taskId Id of the task /// @param role Role of the user /// @param user User that fulfills the designated role event TaskRoleUserSet(uint256 indexed taskId, TaskRole role, address indexed user); /// @notice Event logged when a task payout changes /// @param taskId Id of the task /// @param role Task role whose payout is being changed /// @param token Token of the payout funding /// @param amount Amount of the payout funding event TaskPayoutSet(uint256 indexed taskId, TaskRole role, address token, uint256 amount); /// @notice Event logged when a deliverable has been submitted for a task /// @param taskId Id of the task /// @param deliverableHash Hash of the work performed event TaskDeliverableSubmitted(uint256 indexed taskId, bytes32 deliverableHash); /// @notice Event logged when a task has been completed. This is either because the dueDate has passed /// and the manager closed the task, or the worker has submitted the deliverable. In the /// latter case, TaskDeliverableSubmitted will also be emitted. event TaskCompleted(uint256 indexed taskId); /// @notice Event logged when the rating of a role was revealed /// @param taskId Id of the task /// @param role Role that got rated /// @param rating Rating the role received event TaskWorkRatingRevealed(uint256 indexed taskId, TaskRole role, uint8 rating); /// @notice Event logged when a task has been finalized /// @param taskId Id of the finalized task event TaskFinalized(uint256 indexed taskId); /// @notice Event logged when a payout is claimed, either from a Task or Payment /// @param fundingPotId Id of the funding pot where payout comes from /// @param token Token of the payout claim /// @param amount Amount of the payout claimed, after network fee was deducted event PayoutClaimed(uint256 indexed fundingPotId, address token, uint256 amount); /// @notice Event logged when a task has been canceled /// @param taskId Id of the canceled task event TaskCanceled(uint256 indexed taskId); /// @notice Event logged when a new Domain is added /// @param domainId Id of the newly-created Domain event DomainAdded(uint256 domainId); /// @notice Event logged when a new FundingPot is added /// @param fundingPotId Id of the newly-created FundingPot event FundingPotAdded(uint256 fundingPotId); struct RewardPayoutCycle { // Reputation root hash at the time of reward payout creation bytes32 reputationState; // Colony wide reputation uint256 colonyWideReputation; // Total tokens at the time of reward payout creation uint256 totalTokens; // Amount alocated for reward payout uint256 amount; // Token in which a reward is paid out with address tokenAddress; // Time of creation (in seconds) uint256 blockTimestamp; } struct Payment { address payable recipient; bool finalized; uint256 fundingPotId; uint256 domainId; uint256[] skills; } struct Task { bytes32 specificationHash; bytes32 deliverableHash; TaskStatus status; uint256 dueDate; uint256 fundingPotId; uint256 completionTimestamp; uint256 domainId; uint256[] skills; mapping (uint8 => Role) roles; // Maps task role ids (0,1,2..) to a token amount to be paid on task completion mapping (uint8 => mapping (address => uint256)) payouts; } enum TaskRatings { None, Unsatisfactory, Satisfactory, Excellent } enum TaskRole { Manager, Evaluator, Worker } enum TaskStatus { Active, Cancelled, Finalized } enum ColonyRole { Recovery, Root, Arbitration, Architecture, ArchitectureSubdomain, Funding, Administration } struct Role { // Address of the user for the given role address payable user; // Whether the user failed to submit their rating bool rateFail; // Rating the user received TaskRatings rating; } struct RatingSecrets { uint256 count; uint256 timestamp; mapping (uint8 => bytes32) secret; } // We do have 1 "special" funding pot with id 0 for rewards which will carry the "Unassigned" type. // as they are unrelated to other entities in the Colony the same way the remaining funding pots are releated to domains, tasks and payouts. enum FundingPotAssociatedType { Unassigned, Domain, Task, Payment } struct FundingPot { // Funding pots can store multiple token balances, for ETH use 0x0 address mapping (address => uint256) balance; // Funding pots can be associated with different fundable entities, for now these are: tasks, domains and payments. FundingPotAssociatedType associatedType; uint256 associatedTypeId; // Map any assigned payouts from this pot, note that in Tasks these are broken down to a more granular level on a per role basis mapping (address => uint256) payouts; uint256 payoutsWeCannotMake; } struct Domain { uint256 skillId; uint256 fundingPotId; } uint256 constant MAX_PAYOUT = 2**254 - 1; // Up to 254 bits to account for sign and payout modifiers. }
We do have 1 "special" funding pot with id 0 for rewards which will carry the "Unassigned" type. as they are unrelated to other entities in the Colony the same way the remaining funding pots are releated to domains, tasks and payouts.
enum FundingPotAssociatedType { Unassigned, Domain, Task, Payment }
15,854,345
[ 1, 3218, 741, 1240, 404, 315, 9371, 6, 22058, 5974, 598, 612, 374, 364, 283, 6397, 1492, 903, 9331, 326, 315, 984, 15938, 6, 618, 18, 487, 2898, 854, 640, 9243, 358, 1308, 5140, 316, 326, 1558, 6598, 326, 1967, 4031, 326, 4463, 22058, 5974, 87, 854, 6707, 690, 358, 10128, 16, 4592, 471, 293, 2012, 87, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 2792, 478, 14351, 18411, 19233, 559, 288, 1351, 15938, 16, 6648, 16, 3837, 16, 12022, 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, -100, -100, -100, -100, -100 ]
// Verified using https://dapp.tools // hevm: flattened sources of src/Vesting.sol // SPDX-License-Identifier: MIT AND GPL-3.0-only pragma solidity >=0.8.0 <0.9.0; ////// lib/openzeppelin-contracts/contracts/utils/Context.sol // OpenZeppelin Contracts v4.3.2 (utils/Context.sol) /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.3.2 (access/Ownable.sol) /* pragma solidity ^0.8.0; */ /* import "../utils/Context.sol"; */ /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } ////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) /* pragma solidity ^0.8.0; */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } ////// src/Vesting.sol /* pragma solidity ^0.8.0; */ /* import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; */ /* import "@openzeppelin/contracts/access/Ownable.sol"; */ /** * Tracer Standard Vesting Contract */ contract Vesting is Ownable { struct Schedule { uint256 totalAmount; uint256 claimedAmount; uint256 startTime; uint256 cliffTime; uint256 endTime; bool isFixed; address asset; } // user => scheduleId => schedule mapping(address => mapping(uint256 => Schedule)) public schedules; mapping(address => uint256) public numberOfSchedules; mapping(address => uint256) public locked; event Claim(address indexed claimer, uint256 amount); event Vest(address indexed to, uint256 amount); event Cancelled(address account); constructor() {} /** * @notice Sets up a vesting schedule for a set user. * @dev adds a new Schedule to the schedules mapping. * @param account the account that a vesting schedule is being set up for. Will be able to claim tokens after * the cliff period. * @param amount the amount of tokens being vested for the user. * @param asset the asset that the user is being vested * @param isFixed a flag for if the vesting schedule is fixed or not. Fixed vesting schedules can't be cancelled. * @param cliffWeeks the number of weeks that the cliff will be present at. * @param vestingWeeks the number of weeks the tokens will vest over (linearly) * @param startTime the timestamp for when this vesting should have started */ function vest( address account, uint256 amount, address asset, bool isFixed, uint256 cliffWeeks, uint256 vestingWeeks, uint256 startTime ) public onlyOwner { // ensure cliff is shorter than vesting require( vestingWeeks > 0 && vestingWeeks >= cliffWeeks && amount > 0, "Vesting: invalid vesting params" ); uint256 currentLocked = locked[asset]; // require the token is present require( IERC20(asset).balanceOf(address(this)) >= currentLocked + amount, "Vesting: Not enough tokens" ); // create the schedule uint256 currentNumSchedules = numberOfSchedules[account]; schedules[account][currentNumSchedules] = Schedule( amount, 0, startTime, startTime + (cliffWeeks * 1 weeks), startTime + (vestingWeeks * 1 weeks), isFixed, asset ); numberOfSchedules[account] = currentNumSchedules + 1; locked[asset] = currentLocked + amount; emit Vest(account, amount); } /** * @notice Sets up vesting schedules for multiple users within 1 transaction. * @dev adds a new Schedule to the schedules mapping. * @param accounts an array of the accounts that the vesting schedules are being set up for. * Will be able to claim tokens after the cliff period. * @param amount an array of the amount of tokens being vested for each user. * @param asset the asset that the user is being vested * @param isFixed bool setting if these vesting schedules can be rugged or not. * @param cliffWeeks the number of weeks that the cliff will be present at. * @param vestingWeeks the number of weeks the tokens will vest over (linearly) * @param startTime the timestamp for when this vesting should have started */ function multiVest( address[] calldata accounts, uint256[] calldata amount, address asset, bool isFixed, uint256 cliffWeeks, uint256 vestingWeeks, uint256 startTime ) external onlyOwner { uint256 numberOfAccounts = accounts.length; require( amount.length == numberOfAccounts, "Vesting: Array lengths differ" ); for (uint256 i = 0; i < numberOfAccounts; i++) { vest( accounts[i], amount[i], asset, isFixed, cliffWeeks, vestingWeeks, startTime ); } } /** * @notice allows users to claim vested tokens if the cliff time has passed. * @param scheduleNumber which schedule the user is claiming against */ function claim(uint256 scheduleNumber) external { Schedule storage schedule = schedules[msg.sender][scheduleNumber]; require( schedule.cliffTime <= block.timestamp, "Vesting: cliff not reached" ); require(schedule.totalAmount > 0, "Vesting: not claimable"); // Get the amount to be distributed uint256 amount = calcDistribution( schedule.totalAmount, block.timestamp, schedule.startTime, schedule.endTime ); // Cap the amount at the total amount amount = amount > schedule.totalAmount ? schedule.totalAmount : amount; uint256 amountToTransfer = amount - schedule.claimedAmount; schedule.claimedAmount = amount; // set new claimed amount based off the curve locked[schedule.asset] = locked[schedule.asset] - amountToTransfer; require(IERC20(schedule.asset).transfer(msg.sender, amountToTransfer), "Vesting: transfer failed"); emit Claim(msg.sender, amount); } /** * @notice Allows a vesting schedule to be cancelled. * @dev Any outstanding tokens are returned to the system. * @param account the account of the user whos vesting schedule is being cancelled. */ function rug(address account, uint256 scheduleId) external onlyOwner { Schedule storage schedule = schedules[account][scheduleId]; require(!schedule.isFixed, "Vesting: Account is fixed"); uint256 outstandingAmount = schedule.totalAmount - schedule.claimedAmount; require(outstandingAmount != 0, "Vesting: no outstanding tokens"); schedule.totalAmount = 0; locked[schedule.asset] = locked[schedule.asset] - outstandingAmount; require(IERC20(schedule.asset).transfer(owner(), outstandingAmount), "Vesting: transfer failed"); emit Cancelled(account); } /** * @return calculates the amount of tokens to distribute to an account at any instance in time, based off some * total claimable amount. * @param amount the total outstanding amount to be claimed for this vesting schedule. * @param currentTime the current timestamp. * @param startTime the timestamp this vesting schedule started. * @param endTime the timestamp this vesting schedule ends. */ function calcDistribution( uint256 amount, uint256 currentTime, uint256 startTime, uint256 endTime ) public pure returns (uint256) { // avoid uint underflow if (currentTime < startTime) { return 0; } // if endTime < startTime, this will throw. Since endTime should never be // less than startTime in safe operation, this is fine. return (amount * (currentTime - startTime)) / (endTime - startTime); } /** * @notice Withdraws PHONON tokens from the contract. * @dev blocks withdrawing locked tokens. */ function withdraw(uint256 amount, address asset) external onlyOwner { IERC20 token = IERC20(asset); require( token.balanceOf(address(this)) - locked[asset] >= amount, "Vesting: Can't withdraw" ); require(token.transfer(owner(), amount), "Vesting: withdraw failed"); } }
* @notice Sets up vesting schedules for multiple users within 1 transaction. @dev adds a new Schedule to the schedules mapping. @param accounts an array of the accounts that the vesting schedules are being set up for. Will be able to claim tokens after the cliff period. @param amount an array of the amount of tokens being vested for each user. @param asset the asset that the user is being vested @param isFixed bool setting if these vesting schedules can be rugged or not. @param cliffWeeks the number of weeks that the cliff will be present at. @param vestingWeeks the number of weeks the tokens will vest over (linearly) @param startTime the timestamp for when this vesting should have started/
function multiVest( address[] calldata accounts, uint256[] calldata amount, address asset, bool isFixed, uint256 cliffWeeks, uint256 vestingWeeks, uint256 startTime ) external onlyOwner { uint256 numberOfAccounts = accounts.length; require( amount.length == numberOfAccounts, "Vesting: Array lengths differ" ); for (uint256 i = 0; i < numberOfAccounts; i++) { vest( accounts[i], amount[i], asset, isFixed, cliffWeeks, vestingWeeks, startTime ); } }
5,809,718
[ 1, 2785, 731, 331, 10100, 26720, 364, 3229, 3677, 3470, 404, 2492, 18, 225, 4831, 279, 394, 10674, 358, 326, 26720, 2874, 18, 225, 9484, 392, 526, 434, 326, 9484, 716, 326, 331, 10100, 26720, 854, 3832, 444, 731, 364, 18, 1171, 9980, 506, 7752, 358, 7516, 2430, 1839, 326, 927, 3048, 3879, 18, 225, 3844, 392, 526, 434, 326, 3844, 434, 2430, 3832, 331, 3149, 364, 1517, 729, 18, 225, 3310, 326, 3310, 716, 326, 729, 353, 3832, 331, 3149, 225, 353, 7505, 1426, 3637, 309, 4259, 331, 10100, 26720, 848, 506, 436, 637, 2423, 578, 486, 18, 225, 927, 3048, 6630, 87, 326, 1300, 434, 17314, 716, 326, 927, 3048, 903, 506, 3430, 622, 18, 225, 331, 10100, 6630, 87, 326, 1300, 434, 17314, 326, 2430, 903, 331, 395, 1879, 261, 12379, 715, 13, 225, 8657, 326, 2858, 364, 1347, 333, 331, 10100, 1410, 1240, 5746, 19, 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, 3309, 58, 395, 12, 203, 3639, 1758, 8526, 745, 892, 9484, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 3844, 16, 203, 3639, 1758, 3310, 16, 203, 3639, 1426, 353, 7505, 16, 203, 3639, 2254, 5034, 927, 3048, 6630, 87, 16, 203, 3639, 2254, 5034, 331, 10100, 6630, 87, 16, 203, 3639, 2254, 5034, 8657, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 7922, 13971, 273, 9484, 18, 2469, 31, 203, 3639, 2583, 12, 203, 5411, 3844, 18, 2469, 422, 7922, 13971, 16, 203, 5411, 315, 58, 10100, 30, 1510, 10917, 15221, 6, 203, 3639, 11272, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 7922, 13971, 31, 277, 27245, 288, 203, 5411, 331, 395, 12, 203, 7734, 9484, 63, 77, 6487, 203, 7734, 3844, 63, 77, 6487, 203, 7734, 3310, 16, 203, 7734, 353, 7505, 16, 203, 7734, 927, 3048, 6630, 87, 16, 203, 7734, 331, 10100, 6630, 87, 16, 203, 7734, 8657, 203, 5411, 11272, 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 ]
pragma solidity ^0.4.16; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Manageable * @dev Contract that allows to grant permissions to any address * @dev In real life we are no able to perform all actions with just one Ethereum address * @dev because risks are too high. * @dev Instead owner delegates rights to manage an contract to the different addresses and * @dev stay able to revoke permissions at any time. */ contract Manageable is Ownable { /* Storage */ mapping (address => bool) managerEnabled; // hard switch for a manager - on/off mapping (address => mapping (string => bool)) managerPermissions; // detailed info about manager`s permissions /* Events */ event ManagerEnabledEvent(address indexed manager); event ManagerDisabledEvent(address indexed manager); event ManagerPermissionGrantedEvent(address indexed manager, string permission); event ManagerPermissionRevokedEvent(address indexed manager, string permission); /* Configure contract */ /** * @dev Function to add new manager * @param _manager address New manager */ function enableManager(address _manager) external onlyOwner onlyValidAddress(_manager) { require(managerEnabled[_manager] == false); managerEnabled[_manager] = true; ManagerEnabledEvent(_manager); } /** * @dev Function to remove existing manager * @param _manager address Existing manager */ function disableManager(address _manager) external onlyOwner onlyValidAddress(_manager) { require(managerEnabled[_manager] == true); managerEnabled[_manager] = false; ManagerDisabledEvent(_manager); } /** * @dev Function to grant new permission to the manager * @param _manager address Existing manager * @param _permissionName string Granted permission name */ function grantManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == false); managerPermissions[_manager][_permissionName] = true; ManagerPermissionGrantedEvent(_manager, _permissionName); } /** * @dev Function to revoke permission of the manager * @param _manager address Existing manager * @param _permissionName string Revoked permission name */ function revokeManagerPermission( address _manager, string _permissionName ) external onlyOwner onlyValidAddress(_manager) onlyValidPermissionName(_permissionName) { require(managerPermissions[_manager][_permissionName] == true); managerPermissions[_manager][_permissionName] = false; ManagerPermissionRevokedEvent(_manager, _permissionName); } /* Getters */ /** * @dev Function to check manager status * @param _manager address Manager`s address * @return True if manager is enabled */ function isManagerEnabled(address _manager) public constant onlyValidAddress(_manager) returns (bool) { return managerEnabled[_manager]; } /** * @dev Function to check permissions of a manager * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager has been granted needed permission */ function isPermissionGranted( address _manager, string _permissionName ) public constant onlyValidAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return managerPermissions[_manager][_permissionName]; } /** * @dev Function to check if the manager can perform the action or not * @param _manager address Manager`s address * @param _permissionName string Permission name * @return True if manager is enabled and has been granted needed permission */ function isManagerAllowed( address _manager, string _permissionName ) public constant onlyValidAddress(_manager) onlyValidPermissionName(_permissionName) returns (bool) { return (managerEnabled[_manager] && managerPermissions[_manager][_permissionName]); } /* Helpers */ /** * @dev Modifier to check manager address */ modifier onlyValidAddress(address _manager) { require(_manager != address(0x0)); _; } /** * @dev Modifier to check name of manager permission */ modifier onlyValidPermissionName(string _permissionName) { require(bytes(_permissionName).length != 0); _; } /* Outcome */ /** * @dev Modifier to use in derived contracts */ modifier onlyAllowedManager(string _permissionName) { require(isManagerAllowed(msg.sender, _permissionName) == true); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. * @dev Based on zeppelin's Pausable, but integrated with Manageable * @dev Contract is in paused state by default and should be explicitly unlocked */ contract Pausable is Manageable { /** * Events */ event PauseEvent(); event UnpauseEvent(); /** * Storage */ bool paused = true; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenContractNotPaused() { require(paused == false); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenContractPaused { require(paused == true); _; } /** * @dev called by the manager to pause, triggers stopped state */ function pauseContract() external onlyAllowedManager('pause_contract') whenContractNotPaused { paused = true; PauseEvent(); } /** * @dev called by the manager to unpause, returns to normal state */ function unpauseContract() external onlyAllowedManager('unpause_contract') whenContractPaused { paused = false; UnpauseEvent(); } /** * @dev The getter for "paused" contract variable */ function getPaused() external constant returns (bool) { return paused; } } /** * @title NamedToken */ contract NamedToken { string public name; string public symbol; uint8 public decimals; function NamedToken(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev Function to calculate hash of the token`s name. * @dev Function needed because we can not just return name of the token to another contract - strings have variable length * @return Hash of the token`s name */ function getNameHash() external constant returns (bytes32 result){ return keccak256(name); } /** * @dev Function to calculate hash of the token`s symbol. * @dev Function needed because we can not just return symbol of the token to another contract - strings have variable length * @return Hash of the token`s symbol */ function getSymbolHash() external constant returns (bytes32 result){ return keccak256(symbol); } } /** * @title AngelToken */ contract AngelToken is StandardToken, NamedToken, Pausable { /* Events */ event MintEvent(address indexed account, uint value); event BurnEvent(address indexed account, uint value); event SpendingBlockedEvent(address indexed account); event SpendingUnblockedEvent(address indexed account); /* Storage */ address public centralBankAddress = 0x0; mapping (address => uint) spendingBlocksNumber; /* Constructor */ function AngelToken() public NamedToken('Angel Token', 'ANGL', 18) { centralBankAddress = msg.sender; } /* Methods */ function transfer(address _to, uint _value) public returns (bool) { if (_to != centralBankAddress) { require(!paused); } require(spendingBlocksNumber[msg.sender] == 0); bool result = super.transfer(_to, _value); if (result == true && _to == centralBankAddress) { AngelCentralBank(centralBankAddress).angelBurn(msg.sender, _value); } return result; } function approve(address _spender, uint _value) public whenContractNotPaused returns (bool){ return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint _value) public whenContractNotPaused returns (bool){ require(spendingBlocksNumber[_from] == 0); bool result = super.transferFrom(_from, _to, _value); if (result == true && _to == centralBankAddress) { AngelCentralBank(centralBankAddress).angelBurn(_from, _value); } return result; } function mint(address _account, uint _value) external onlyAllowedManager('mint_tokens') { balances[_account] = balances[_account].add(_value); totalSupply = totalSupply.add(_value); MintEvent(_account, _value); Transfer(address(0x0), _account, _value); // required for blockexplorers } function burn(uint _value) external onlyAllowedManager('burn_tokens') { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); BurnEvent(msg.sender, _value); } function blockSpending(address _account) external onlyAllowedManager('block_spending') { spendingBlocksNumber[_account] = spendingBlocksNumber[_account].add(1); SpendingBlockedEvent(_account); } function unblockSpending(address _account) external onlyAllowedManager('unblock_spending') { spendingBlocksNumber[_account] = spendingBlocksNumber[_account].sub(1); SpendingUnblockedEvent(_account); } } /** * @title AngelCentralBank * * @dev Crowdsale and escrow contract */ contract AngelCentralBank { /* Data structures */ struct InvestmentRecord { uint tokensSoldBeforeWei; uint investedEthWei; uint purchasedTokensWei; uint refundedEthWei; uint returnedTokensWei; } /* Storage - config */ uint public constant icoCap = 70000000 * (10 ** 18); uint public initialTokenPrice = 1 * (10 ** 18) / (10 ** 4); // means 0.0001 ETH for one token uint public constant landmarkSize = 1000000 * (10 ** 18); uint public constant landmarkPriceStepNumerator = 10; uint public constant landmarkPriceStepDenominator = 100; uint public constant firstRefundRoundRateNumerator = 80; uint public constant firstRefundRoundRateDenominator = 100; uint public constant secondRefundRoundRateNumerator = 40; uint public constant secondRefundRoundRateDenominator = 100; uint public constant initialFundsReleaseNumerator = 20; // part of investment uint public constant initialFundsReleaseDenominator = 100; uint public constant afterFirstRefundRoundFundsReleaseNumerator = 50; // part of remaining funds uint public constant afterFirstRefundRoundFundsReleaseDenominator = 100; uint public constant angelFoundationShareNumerator = 30; uint public constant angelFoundationShareDenominator = 100; /* Storage - state */ address public angelFoundationAddress = address(0x2b0556a6298eA3D35E90F1df32cc126b31F59770); uint public icoLaunchTimestamp = 1511784000; // November 27th 12:00 GMT uint public icoFinishTimestamp = 1513727999; // December 19th 23:59:59 GMT uint public firstRefundRoundFinishTimestamp = 1520424000; // March 7th 2018 12:00 GMT uint public secondRefundRoundFinishTimestamp = 1524744000; // April 26th 2018 12:00 GMT AngelToken public angelToken; mapping (address => InvestmentRecord[]) public investments; // investorAddress => list of investments mapping (address => bool) public investors; uint public totalInvestors = 0; uint public totalTokensSold = 0; bool isIcoFinished = false; bool firstRefundRoundFundsWithdrawal = false; /* Events */ event InvestmentEvent(address indexed investor, uint eth, uint angel); event RefundEvent(address indexed investor, uint eth, uint angel); /* Constructor and config */ function AngelCentralBank() public { angelToken = new AngelToken(); angelToken.enableManager(address(this)); angelToken.grantManagerPermission(address(this), 'mint_tokens'); angelToken.grantManagerPermission(address(this), 'burn_tokens'); angelToken.grantManagerPermission(address(this), 'unpause_contract'); angelToken.transferOwnership(angelFoundationAddress); } /* Investments */ /** * @dev Fallback function receives ETH and sends tokens back */ function () public payable { angelRaise(); } /** * @dev Process new ETH investment and sends tokens back */ function angelRaise() internal { require(msg.value > 0); require(now >= icoLaunchTimestamp && now < icoFinishTimestamp); // calculate amount of tokens for received ETH uint _purchasedTokensWei = 0; uint _notProcessedEthWei = 0; (_purchasedTokensWei, _notProcessedEthWei) = calculatePurchasedTokens(totalTokensSold, msg.value); uint _actualInvestment = (msg.value - _notProcessedEthWei); // create record for the investment uint _newRecordIndex = investments[msg.sender].length; investments[msg.sender].length += 1; investments[msg.sender][_newRecordIndex].tokensSoldBeforeWei = totalTokensSold; investments[msg.sender][_newRecordIndex].investedEthWei = _actualInvestment; investments[msg.sender][_newRecordIndex].purchasedTokensWei = _purchasedTokensWei; investments[msg.sender][_newRecordIndex].refundedEthWei = 0; investments[msg.sender][_newRecordIndex].returnedTokensWei = 0; // calculate stats if (investors[msg.sender] == false) { totalInvestors += 1; } investors[msg.sender] = true; totalTokensSold += _purchasedTokensWei; // transfer tokens and ETH angelToken.mint(msg.sender, _purchasedTokensWei); angelToken.mint(angelFoundationAddress, _purchasedTokensWei * angelFoundationShareNumerator / (angelFoundationShareDenominator - angelFoundationShareNumerator)); angelFoundationAddress.transfer(_actualInvestment * initialFundsReleaseNumerator / initialFundsReleaseDenominator); if (_notProcessedEthWei > 0) { msg.sender.transfer(_notProcessedEthWei); } // finish ICO if cap reached if (totalTokensSold >= icoCap) { icoFinishTimestamp = now; finishIco(); } // fire event InvestmentEvent(msg.sender, _actualInvestment, _purchasedTokensWei); } /** * @dev Calculate amount of tokens for received ETH * @param _totalTokensSoldBefore uint Amount of tokens sold before this investment [token wei] * @param _investedEthWei uint Investment amount [ETH wei] * @return Purchased amount of tokens [token wei] */ function calculatePurchasedTokens( uint _totalTokensSoldBefore, uint _investedEthWei) constant public returns (uint _purchasedTokensWei, uint _notProcessedEthWei) { _purchasedTokensWei = 0; _notProcessedEthWei = _investedEthWei; uint _landmarkPrice; uint _maxLandmarkTokensWei; uint _maxLandmarkEthWei; bool _isCapReached = false; do { // get landmark values _landmarkPrice = calculateLandmarkPrice(_totalTokensSoldBefore + _purchasedTokensWei); _maxLandmarkTokensWei = landmarkSize - ((_totalTokensSoldBefore + _purchasedTokensWei) % landmarkSize); if (_totalTokensSoldBefore + _purchasedTokensWei + _maxLandmarkTokensWei >= icoCap) { _maxLandmarkTokensWei = icoCap - _totalTokensSoldBefore - _purchasedTokensWei; _isCapReached = true; } _maxLandmarkEthWei = _maxLandmarkTokensWei * _landmarkPrice / (10 ** 18); // check investment against landmark values if (_notProcessedEthWei >= _maxLandmarkEthWei) { _purchasedTokensWei += _maxLandmarkTokensWei; _notProcessedEthWei -= _maxLandmarkEthWei; } else { _purchasedTokensWei += _notProcessedEthWei * (10 ** 18) / _landmarkPrice; _notProcessedEthWei = 0; } } while ((_notProcessedEthWei > 0) && (_isCapReached == false)); assert(_purchasedTokensWei > 0); return (_purchasedTokensWei, _notProcessedEthWei); } /* Refunds */ function angelBurn( address _investor, uint _returnedTokensWei ) external returns (uint) { require(msg.sender == address(angelToken)); require(now >= icoLaunchTimestamp && now < secondRefundRoundFinishTimestamp); uint _notProcessedTokensWei = _returnedTokensWei; uint _refundedEthWei = 0; uint _allRecordsNumber = investments[_investor].length; uint _recordMaxReturnedTokensWei = 0; uint _recordTokensWeiToProcess = 0; uint _tokensSoldWei = 0; uint _recordRefundedEthWei = 0; uint _recordNotProcessedTokensWei = 0; for (uint _recordID = 0; _recordID < _allRecordsNumber; _recordID += 1) { if (investments[_investor][_recordID].purchasedTokensWei <= investments[_investor][_recordID].returnedTokensWei || investments[_investor][_recordID].investedEthWei <= investments[_investor][_recordID].refundedEthWei) { // tokens already refunded continue; } // calculate amount of tokens to refund with this record _recordMaxReturnedTokensWei = investments[_investor][_recordID].purchasedTokensWei - investments[_investor][_recordID].returnedTokensWei; _recordTokensWeiToProcess = (_notProcessedTokensWei < _recordMaxReturnedTokensWei) ? _notProcessedTokensWei : _recordMaxReturnedTokensWei; assert(_recordTokensWeiToProcess > 0); // calculate amount of ETH to send back _tokensSoldWei = investments[_investor][_recordID].tokensSoldBeforeWei + investments[_investor][_recordID].returnedTokensWei; (_recordRefundedEthWei, _recordNotProcessedTokensWei) = calculateRefundedEth(_tokensSoldWei, _recordTokensWeiToProcess); if (_recordRefundedEthWei > (investments[_investor][_recordID].investedEthWei - investments[_investor][_recordID].refundedEthWei)) { // this can happen due to rounding error _recordRefundedEthWei = (investments[_investor][_recordID].investedEthWei - investments[_investor][_recordID].refundedEthWei); } assert(_recordRefundedEthWei > 0); assert(_recordNotProcessedTokensWei == 0); // persist changes to the storage _refundedEthWei += _recordRefundedEthWei; _notProcessedTokensWei -= _recordTokensWeiToProcess; investments[_investor][_recordID].refundedEthWei += _recordRefundedEthWei; investments[_investor][_recordID].returnedTokensWei += _recordTokensWeiToProcess; assert(investments[_investor][_recordID].refundedEthWei <= investments[_investor][_recordID].investedEthWei); assert(investments[_investor][_recordID].returnedTokensWei <= investments[_investor][_recordID].purchasedTokensWei); // stop if we already refunded all tokens if (_notProcessedTokensWei == 0) { break; } } // throw if we do not have tokens to refund require(_notProcessedTokensWei < _returnedTokensWei); require(_refundedEthWei > 0); // calculate refund discount uint _refundedEthWeiWithDiscount = calculateRefundedEthWithDiscount(_refundedEthWei); // transfer ETH and remaining tokens angelToken.burn(_returnedTokensWei - _notProcessedTokensWei); if (_notProcessedTokensWei > 0) { angelToken.transfer(_investor, _notProcessedTokensWei); } _investor.transfer(_refundedEthWeiWithDiscount); // fire event RefundEvent(_investor, _refundedEthWeiWithDiscount, _returnedTokensWei - _notProcessedTokensWei); } /** * @dev Calculate discounted amount of ETH for refunded tokens * @param _refundedEthWei uint Calculated amount of ETH to refund [ETH wei] * @return Discounted amount of ETH for refunded [ETH wei] */ function calculateRefundedEthWithDiscount( uint _refundedEthWei ) public constant returns (uint) { if (now <= firstRefundRoundFinishTimestamp) { return (_refundedEthWei * firstRefundRoundRateNumerator / firstRefundRoundRateDenominator); } else { return (_refundedEthWei * secondRefundRoundRateNumerator / secondRefundRoundRateDenominator); } } /** * @dev Calculate amount of ETH for refunded tokens. Just abstract price ladder * @param _totalTokensSoldBefore uint Amount of tokens that have been sold (starting point) [token wei] * @param _returnedTokensWei uint Amount of tokens to refund [token wei] * @return Refunded amount of ETH [ETH wei] (without discounts) */ function calculateRefundedEth( uint _totalTokensSoldBefore, uint _returnedTokensWei ) public constant returns (uint _refundedEthWei, uint _notProcessedTokensWei) { _refundedEthWei = 0; uint _refundedTokensWei = 0; _notProcessedTokensWei = _returnedTokensWei; uint _landmarkPrice = 0; uint _maxLandmarkTokensWei = 0; uint _maxLandmarkEthWei = 0; bool _isCapReached = false; do { // get landmark values _landmarkPrice = calculateLandmarkPrice(_totalTokensSoldBefore + _refundedTokensWei); _maxLandmarkTokensWei = landmarkSize - ((_totalTokensSoldBefore + _refundedTokensWei) % landmarkSize); if (_totalTokensSoldBefore + _refundedTokensWei + _maxLandmarkTokensWei >= icoCap) { _maxLandmarkTokensWei = icoCap - _totalTokensSoldBefore - _refundedTokensWei; _isCapReached = true; } _maxLandmarkEthWei = _maxLandmarkTokensWei * _landmarkPrice / (10 ** 18); // check investment against landmark values if (_notProcessedTokensWei > _maxLandmarkTokensWei) { _refundedEthWei += _maxLandmarkEthWei; _refundedTokensWei += _maxLandmarkTokensWei; _notProcessedTokensWei -= _maxLandmarkTokensWei; } else { _refundedEthWei += _notProcessedTokensWei * _landmarkPrice / (10 ** 18); _refundedTokensWei += _notProcessedTokensWei; _notProcessedTokensWei = 0; } } while ((_notProcessedTokensWei > 0) && (_isCapReached == false)); assert(_refundedEthWei > 0); return (_refundedEthWei, _notProcessedTokensWei); } /* Calculation of the price */ /** * @dev Calculate price for tokens * @param _totalTokensSoldBefore uint Amount of tokens sold before [token wei] * @return Calculated price */ function calculateLandmarkPrice(uint _totalTokensSoldBefore) public constant returns (uint) { return initialTokenPrice + initialTokenPrice * landmarkPriceStepNumerator / landmarkPriceStepDenominator * (_totalTokensSoldBefore / landmarkSize); } /* Lifecycle */ function finishIco() public { require(now >= icoFinishTimestamp); require(isIcoFinished == false); isIcoFinished = true; angelToken.unpauseContract(); } function withdrawFoundationFunds() external { require(now > firstRefundRoundFinishTimestamp); if (now > firstRefundRoundFinishTimestamp && now <= secondRefundRoundFinishTimestamp) { require(firstRefundRoundFundsWithdrawal == false); firstRefundRoundFundsWithdrawal = true; angelFoundationAddress.transfer(this.balance * afterFirstRefundRoundFundsReleaseNumerator / afterFirstRefundRoundFundsReleaseDenominator); } else { angelFoundationAddress.transfer(this.balance); } } }
transfer tokens and ETH
angelToken.mint(msg.sender, _purchasedTokensWei);
13,138,691
[ 1, 13866, 2430, 471, 512, 2455, 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, 565, 7603, 292, 1345, 18, 81, 474, 12, 3576, 18, 15330, 16, 389, 12688, 343, 8905, 5157, 3218, 77, 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 ]
// SPDX-License-Identifier: Apache-2.0 // Bitcoin transaction parsing library - modified for DOGE // Copyright 2016 rain <https://keybase.io/rain> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // https://en.bitcoin.it/wiki/Protocol_documentation#tx // // Raw Bitcoin transaction structure: // // field | size | type | description // version | 4 | int32 | transaction version number // n_tx_in | 1-9 | var_int | number of transaction inputs // tx_in | 41+ | tx_in[] | list of transaction inputs // n_tx_out | 1-9 | var_int | number of transaction outputs // tx_out | 9+ | tx_out[] | list of transaction outputs // lock_time | 4 | uint32 | block number / timestamp at which tx locked // // Transaction input (tx_in) structure: // // field | size | type | description // previous | 36 | outpoint | Previous output transaction reference // script_len | 1-9 | var_int | Length of the signature script // sig_script | ? | uchar[] | Script for confirming transaction authorization // sequence | 4 | uint32 | Sender transaction version // // OutPoint structure: // // field | size | type | description // hash | 32 | char[32] | The hash of the referenced transaction // index | 4 | uint32 | The index of this output in the referenced transaction // // Transaction output (tx_out) structure: // // field | size | type | description // value | 8 | int64 | Transaction value (Satoshis) // pk_script_len | 1-9 | var_int | Length of the public key script // pk_script | ? | uchar[] | Public key as a Bitcoin script. // // Variable integers (var_int) can be encoded differently depending // on the represented value, to save space. Variable integers always // precede an array of a variable length data type (e.g. tx_in). // // Variable integer encodings as a function of represented value: // // value | bytes | format // <0xFD (253) | 1 | uint8 // <=0xFFFF (65535)| 3 | 0xFD followed by length as uint16 // <=0xFFFF FFFF | 5 | 0xFE followed by length as uint32 // - | 9 | 0xFF followed by length as uint64 // // Public key scripts `pk_script` are set on the output and can // take a number of forms. The regular transaction script is // called 'pay-to-pubkey-hash' (P2PKH): // // OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG // // OP_x are Bitcoin script opcodes. The bytes representation (including // the 0x14 20-byte stack push) is: // // 0x76 0xA9 0x14 <pubKeyHash> 0x88 0xAC // // The <pubKeyHash> is the ripemd160 hash of the sha256 hash of // the public key, preceded by a network version byte. (21 bytes total) // // Network version bytes: 0x00 (mainnet); 0x6f (testnet); 0x34 (namecoin) // // The Bitcoin address is derived from the pubKeyHash. The binary form is the // pubKeyHash, plus a checksum at the end. The checksum is the first 4 bytes // of the (32 byte) double sha256 of the pubKeyHash. (25 bytes total) // This is converted to base58 to form the publicly used Bitcoin address. // Mainnet P2PKH transaction scripts are to addresses beginning with '1'. // // P2SH ('pay to script hash') scripts only supply a script hash. The spender // must then provide the script that would allow them to redeem this output. // This allows for arbitrarily complex scripts to be funded using only a // hash of the script, and moves the onus on providing the script from // the spender to the redeemer. // // The P2SH script format is simple: // // OP_HASH160 <scriptHash> OP_EQUAL // // 0xA9 0x14 <scriptHash> 0x87 // // The <scriptHash> is the ripemd160 hash of the sha256 hash of the // redeem script. The P2SH address is derived from the scriptHash. // Addresses are the scriptHash with a version prefix of 5, encoded as // Base58check. These addresses begin with a '3'. pragma solidity ^0.7.6; // parse a raw Dogecoin transaction byte array library DogeMessageLibrary { uint constant p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f; // secp256k1 uint constant q = (p + 1) / 4; // Error codes uint constant ERR_INVALID_HEADER = 10050; uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Litecoin merkle isn't 0 uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root isn't in the first 20 bytes of coinbase tx uint constant ERR_CHAIN_MERKLE = 10110; uint constant ERR_PARENT_MERKLE = 10120; uint constant ERR_PROOF_OF_WORK = 10130; enum Network { MAINNET, TESTNET, REGTEST } // AuxPoW block fields struct AuxPoW { uint scryptHash; uint txHash; uint coinbaseMerkleRoot; // Merkle root of auxiliary block hash tree; stored in coinbase tx field uint[] chainMerkleProof; // proves that a given Dogecoin block hash belongs to a tree with the above root uint dogeHashIndex; // index of Doge block hash within block hash tree uint coinbaseMerkleRootCode; // encodes whether or not the root was found properly uint parentMerkleRoot; // Merkle root of transaction tree from parent Litecoin block header uint[] parentMerkleProof; // proves that coinbase tx belongs to a tree with the above root uint coinbaseTxIndex; // index of coinbase tx within Litecoin tx tree uint parentNonce; } // Dogecoin block header stored as a struct, mostly for readability purposes. // BlockHeader structs can be obtained by parsing a block header's first 80 bytes // with parseHeaderBytes. struct BlockHeader { uint32 version; uint32 time; uint32 bits; uint32 nonce; uint blockHash; uint prevBlock; uint merkleRoot; } struct InputDescriptor { // Byte offset where the input is located in the tx uint offset; // Byte offset where the signature script is located in the tx uint sigScriptOffset; // Length of the signature script uint sigScriptLength; } /** * Convert a variable integer into a Solidity numeric type. * * @return the integer as a uint256 * @return the byte index after the var integer */ function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) { // the first byte tells us how big the integer is uint8 ibit = uint8(txBytes[pos]); pos += 1; // skip ibit if (ibit < 0xfd) { return (ibit, pos); } else if (ibit == 0xfd) { return (getBytesLE(txBytes, pos, 16), pos + 2); } else if (ibit == 0xfe) { return (getBytesLE(txBytes, pos, 32), pos + 4); } else /*if (ibit == 0xff)*/ { return (getBytesLE(txBytes, pos, 64), pos + 8); } } // Convert little endian bytes to uint function getBytesLE(bytes memory data, uint pos, uint bits) internal pure returns (uint) { if (bits == 8) { return uint8(data[pos]); } else if (bits == 16) { return uint16(uint8(data[pos])) + uint16(uint8(data[pos + 1])) * 2 ** 8; } else if (bits == 32) { return uint32(uint8(data[pos])) + uint32(uint8(data[pos + 1])) * 2 ** 8 + uint32(uint8(data[pos + 2])) * 2 ** 16 + uint32(uint8(data[pos + 3])) * 2 ** 24; } else if (bits == 64) { return uint64(uint8(data[pos])) + uint64(uint8(data[pos + 1])) * 2 ** 8 + uint64(uint8(data[pos + 2])) * 2 ** 16 + uint64(uint8(data[pos + 3])) * 2 ** 24 + uint64(uint8(data[pos + 4])) * 2 ** 32 + uint64(uint8(data[pos + 5])) * 2 ** 40 + uint64(uint8(data[pos + 6])) * 2 ** 48 + uint64(uint8(data[pos + 7])) * 2 ** 56; } else { revert("Invalid bits parameter in getBytesLE"); } } // @dev - Parses a doge tx // // @param txBytes - tx byte array // @param expectedOperatorPKH - public key hash that is expected to be used as output or input // Outputs // @return userOutputValue - amount sent to the unlock address in satoshis // @return operatorChangePresent - if true, indicates that the operator sent some change to his address. // @return operatorOutputValue - amount of the operator change output // @return operatorOutputIndex - number of the operator change output in the tx function parseUnlockTransaction( bytes memory txBytes, bytes20 expectedOperatorPKH ) internal pure returns (uint, uint, uint16) { uint pos; // skip version pos = 4; /* Inputs One or more inputs signed by the operator. Ouputs 0. Output for the user. This is ignored. 1. Optional. Operator change. */ pos = checkUnlockInputs(txBytes, pos, expectedOperatorPKH); return parseUnlockTxOutputs(expectedOperatorPKH, txBytes, pos); } function checkUnlockInputs( bytes memory txBytes, uint pos, bytes20 expectedOperatorPKH ) private pure returns (uint) { InputDescriptor[] memory inputScripts; (inputScripts, pos) = scanInputs(txBytes, pos, 0); for (uint i = 0; i < inputScripts.length; i++) { (bytes32 inputPubKey, bool inputPubKeyOdd) = getInputPubKey(txBytes, inputScripts[i]); require( expectedOperatorPKH == pub2PubKeyHash(inputPubKey, inputPubKeyOdd), "Invalid unlock tx. One of the inputs is not signed by the operator." ); } return pos; } // Determine the operator output, if any, and the value of the user output // // @param expectedOperatorPKH - operator public key hash // @param txBytes - tx byte array // @param pos - position to start parsing txBytes // Outputs // @return output value of operator output // @return output index of operator output // @return lockDestinationEthAddress - Lock destination address if operator output and OP_RETURN output found, 0 otherwise // // Returns output amount, index and ethereum address function parseUnlockTxOutputs( bytes20 expectedOperatorPKH, bytes memory txBytes, uint pos ) private pure returns (uint, uint, uint16) { /* Ouputs 0. Output for the user. This output is ignored. 1. Optional. Operator change. */ (uint userOutputValue, uint operatorChangeScriptStart, uint operatorChangeScriptLength, uint operatorChangeValue) = scanUnlockOutputs(txBytes, pos); // TODO: abstract this check into a function? // Check if the change output exists if (operatorChangeScriptStart < txBytes.length) { // Check tx is sending funds to an operator. bytes20 outputPublicKeyHash = parseP2PKHOutputScript(txBytes, operatorChangeScriptStart, operatorChangeScriptLength); require( outputPublicKeyHash == expectedOperatorPKH, "Invalid unlock tx. The second tx output does not have a P2PKH output script for an operator." ); return (userOutputValue, operatorChangeValue, 1); } return (userOutputValue, 0, 0); } // Scan the outputs of an unlock transaction. // The first output in an unlock transaction transfers value to a user. // The second output in an unlock transaction may be change for the operator. // Returns the value unlocked for the user output and the value, offset and length of scripts // for the operator change output, if any. function scanUnlockOutputs( bytes memory txBytes, uint pos ) private pure returns (uint, uint, uint, uint) { uint nOutputs; (nOutputs, pos) = parseVarInt(txBytes, pos); require(nOutputs == 1 || nOutputs == 2, "Unlock transactions only have one or two outputs."); // Tx output 0 is for the user // read value of the output for the user uint firstOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; // read the script length uint firstOutputScriptLength; (firstOutputScriptLength, pos) = parseVarInt(txBytes, pos); // uint firstOutputScriptStart = pos; pos += firstOutputScriptLength; uint secondOutputScriptLength; uint secondOutputScriptStart = txBytes.length; uint secondOutputValue; if (nOutputs == 2) { // Tx output 1 is the change for the operator // read value of operator change secondOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; (secondOutputScriptLength, secondOutputScriptStart) = parseVarInt(txBytes, pos); } return (firstOutputValue, secondOutputScriptStart, secondOutputScriptLength, secondOutputValue); } // @dev - Parses a doge tx assuming it is a lock operation // // @param txBytes - tx byte array // @param expectedOperatorPKH - public key hash that is expected to be used as output or input // Outputs // @return outputValue - amount sent to the lock address in satoshis // @return lockDestinationEthAddress - address where tokens should be minted to // @return outputIndex - number of output where expectedOperatorPKH was found function parseLockTransaction( bytes memory txBytes, bytes20 expectedOperatorPKH ) internal pure returns (uint, address, uint16) { uint pos; // skip version pos = 4; // Ignore inputs pos = skipInputs(txBytes, pos); address lockDestinationEthAddress; uint operatorTxOutputValue; (operatorTxOutputValue, lockDestinationEthAddress) = parseLockTxOutputs(expectedOperatorPKH, txBytes, pos); require(lockDestinationEthAddress != address(0x0)); return (operatorTxOutputValue, lockDestinationEthAddress, 0); } // Parse operator output and embedded ethereum address in transaction outputs in tx // // @param expectedOperatorPKH - operator public key hash to look for // @param txBytes - tx byte array // @param pos - position to start parsing txBytes // Outputs // @return output value of operator output // @return output index of operator output // @return lockDestinationEthAddress - Lock destination address if operator output and OP_RETURN output found, 0 otherwise // // Returns output amount, index and ethereum address function parseLockTxOutputs( bytes20 expectedOperatorPKH, bytes memory txBytes, uint pos ) private pure returns (uint, address) { /* Outputs 0. Operator 1. OP_RETURN with the ethereum address of the user 2. Optional. Change output for the user. This output is ignored. */ uint operatorOutputValue; uint operatorScriptStart; uint operatorScriptLength; uint ethAddressScriptStart; uint ethAddressScriptLength; (operatorOutputValue, operatorScriptStart, operatorScriptLength, ethAddressScriptStart, ethAddressScriptLength) = scanLockOutputs(txBytes, pos); // Check tx is sending funds to an operator. bytes20 outputPublicKeyHash = parseP2PKHOutputScript(txBytes, operatorScriptStart, operatorScriptLength); require(outputPublicKeyHash == expectedOperatorPKH, "The first tx output does not have a P2PKH output script for an operator."); // Read the destination Ethereum address require(isEthereumAddress(txBytes, ethAddressScriptStart, ethAddressScriptLength), "The second tx output does not describe an ethereum address."); address lockDestinationEthAddress = readEthereumAddress(txBytes, ethAddressScriptStart, ethAddressScriptLength); return (operatorOutputValue, lockDestinationEthAddress); } // Scan the outputs of a lock transaction. // The first output in a lock transaction transfers value to an operator. // The second output in a lock transaction is an unspendable output with an ethereum address. // Returns the offsets and lengths of scripts for the first and second outputs and // the value of the first output. function scanLockOutputs(bytes memory txBytes, uint pos) private pure returns (uint, uint, uint, uint, uint) { uint nOutputs; (nOutputs, pos) = parseVarInt(txBytes, pos); require(nOutputs == 2 || nOutputs == 3, "Lock transactions only have two or three outputs."); // Tx output 0 is for the operator // read value of the output for the operator uint operatorOutputValue = getBytesLE(txBytes, pos, 64); pos += 8; // read the script length uint operatorScriptLength; (operatorScriptLength, pos) = parseVarInt(txBytes, pos); uint operatorScriptStart = pos; pos += operatorScriptLength; // Tx output 1 describes the ethereum address that should receive the dogecoin tokens // skip value pos += 8; uint ethAddressScriptLength; uint ethAddressScriptStart; (ethAddressScriptLength, ethAddressScriptStart) = parseVarInt(txBytes, pos); return (operatorOutputValue, operatorScriptStart, operatorScriptLength, ethAddressScriptStart, ethAddressScriptLength); } function getInputPubKey(bytes memory txBytes, InputDescriptor memory input) private pure returns (bytes32, bool) { bytes32 pubKey; bool odd; (, pubKey, odd,) = parseScriptSig(txBytes, input.sigScriptOffset); return (pubKey, odd); } // Scan the inputs and find the script lengths. // @return an array of script descriptors. Each one describes the length and the start position // of the script. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanInputs(bytes memory txBytes, uint pos, uint stop) private pure returns (InputDescriptor[] memory, uint) { uint nInputs; uint halt; (nInputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > nInputs) { halt = nInputs; } else { halt = stop; } InputDescriptor[] memory inputs = new InputDescriptor[](halt); for (uint256 i = 0; i < halt; i++) { inputs[i].offset = pos; // skip outpoint pos += 36; uint scriptLength; (scriptLength, pos) = parseVarInt(txBytes, pos); inputs[i].sigScriptOffset = pos; inputs[i].sigScriptLength = scriptLength; // skip sig_script, seq pos += scriptLength + 4; } return (inputs, pos); } /** * Consumes all inputs in a transaction without storing anything in memory * @return index to tx output quantity var integer */ function skipInputs(bytes memory txBytes, uint pos) private pure returns (uint) { uint n_inputs; (n_inputs, pos) = parseVarInt(txBytes, pos); for (uint256 i = 0; i < n_inputs; i++) { // skip outpoint pos += 36; uint script_len; (script_len, pos) = parseVarInt(txBytes, pos); // skip sig_script and seq pos += script_len + 4; } return pos; } // similar to scanInputs, but consumes less gas since it doesn't store the inputs // also returns position of coinbase tx for later use function skipInputsAndGetScriptPos(bytes memory txBytes, uint pos, uint stop) private pure returns (uint, uint) { uint script_pos; uint n_inputs; uint halt; uint script_len; (n_inputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_inputs) { halt = n_inputs; } else { halt = stop; } for (uint256 i = 0; i < halt; i++) { pos += 36; // skip outpoint (script_len, pos) = parseVarInt(txBytes, pos); if (i == 0) script_pos = pos; // first input script begins where first script length ends // (script_len, pos) = (1, 0); pos += script_len + 4; // skip sig_script, seq } return (pos, script_pos); } // scan the outputs and find the values and script lengths. // return array of values, array of script lengths and the // end position of the outputs. // takes a 'stop' argument which sets the maximum number of // outputs to scan through. stop=0 => scan all. function scanOutputs(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint[] memory, uint[] memory, uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } uint[] memory script_starts = new uint[](halt); uint[] memory script_lens = new uint[](halt); uint[] memory output_values = new uint[](halt); for (uint256 i = 0; i < halt; i++) { output_values[i] = getBytesLE(txBytes, pos, 64); pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); script_starts[i] = pos; script_lens[i] = script_len; pos += script_len; } return (output_values, script_starts, script_lens, pos); } // similar to scanOutputs, but consumes less gas since it doesn't store the outputs function skipOutputs(bytes memory txBytes, uint pos, uint stop) private pure returns (uint) { uint n_outputs; uint halt; uint script_len; (n_outputs, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_outputs) { halt = n_outputs; } else { halt = stop; } for (uint256 i = 0; i < halt; i++) { pos += 8; (script_len, pos) = parseVarInt(txBytes, pos); pos += script_len; } return pos; } // get final position of inputs, outputs and lock time // this is a helper function to slice a byte array and hash the inputs, outputs and lock time function getSlicePosAndScriptPos(bytes memory txBytes, uint pos) private pure returns (uint slicePos, uint scriptPos) { (slicePos, scriptPos) = skipInputsAndGetScriptPos(txBytes, pos + 4, 0); slicePos = skipOutputs(txBytes, slicePos, 0); slicePos += 4; // skip lock time } // scan a Merkle branch. // return array of values and the end position of the sibling hashes. // takes a 'stop' argument which sets the maximum number of // siblings to scan through. stop=0 => scan all. function scanMerkleBranch(bytes memory txBytes, uint pos, uint stop) private pure returns (uint[] memory, uint) { uint n_siblings; uint halt; (n_siblings, pos) = parseVarInt(txBytes, pos); if (stop == 0 || stop > n_siblings) { halt = n_siblings; } else { halt = stop; } uint[] memory sibling_values = new uint[](halt); for (uint256 i = 0; i < halt; i++) { sibling_values[i] = flip32Bytes(sliceBytes32Int(txBytes, pos)); pos += 32; } return (sibling_values, pos); } // Slice 20 contiguous bytes from bytes `data`, starting at `start` function sliceBytes20(bytes memory data, uint start) private pure returns (bytes20) { uint160 slice = 0; // FIXME: With solc v0.4.24 and optimizations enabled // using uint160 for index i will generate an error // "Error: VM Exception while processing transaction: Error: redPow(normalNum)" for (uint256 i = 0; i < 20; i++) { slice += uint160(uint8(data[i + start])) << uint160(8 * (19 - i)); } return bytes20(slice); } // Slice 32 contiguous bytes from bytes `data`, starting at `start` function sliceBytes32Int(bytes memory data, uint start) private pure returns (uint slice) { for (uint i = 0; i < 32; i++) { if (i + start < data.length) { slice += uint(uint8(data[i + start])) << (8 * (31 - i)); } } } // @dev returns a portion of a given byte array specified by its starting and ending points // Should be private, made internal for testing // Breaks underscore naming convention for parameters because it raises a compiler error // if `offset` is changed to `_offset`. // // @param _rawBytes - array to be sliced // @param offset - first byte of sliced array // @param _endIndex - last byte of sliced array function sliceArray(bytes memory _rawBytes, uint offset, uint _endIndex) internal view returns (bytes memory) { uint len = _endIndex - offset; bytes memory result = new bytes(len); assembly { // Call precompiled contract to copy data if iszero(staticcall(gas(), 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) { revert(0, 0) } } return result; } // returns true if the bytes located in txBytes by pos and // script_len represent a P2PKH script function isP2PKH(bytes memory txBytes, uint pos, uint script_len) private pure returns (bool) { return (script_len == 25) // 20 byte pubkeyhash + 5 bytes of script && (txBytes[pos] == 0x76) // OP_DUP && (txBytes[pos + 1] == 0xa9) // OP_HASH160 && (txBytes[pos + 2] == 0x14) // bytes to push && (txBytes[pos + 23] == 0x88) // OP_EQUALVERIFY && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG } // Get the pubkeyhash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) outputs. // Returns the pubkeyhash, or zero if unknown output. function parseP2PKHOutputScript(bytes memory txBytes, uint pos, uint script_len) private pure returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else { return bytes20(0); } } // Parse a P2PKH scriptSig // TODO: add script length as a parameter? function parseScriptSig(bytes memory txBytes, uint pos) private pure returns (bytes memory, bytes32, bool, uint) { bytes memory sig; bytes32 pubKey; bool odd; // TODO: do we want the signature? (sig, pos) = parseSignature(txBytes, pos); (pubKey, odd, pos) = parsePubKey(txBytes, pos); return (sig, pubKey, odd, pos); } // Extract a signature function parseSignature(bytes memory txBytes, uint pos) private pure returns (bytes memory, uint) { uint8 op; bytes memory sig; (op, pos) = getOpcode(txBytes, pos); require(op >= 9 && op <= 73); require(uint8(txBytes[pos]) == 0x30); //FIXME: Copy signature pos += op; return (sig, pos); } // Extract public key function parsePubKey(bytes memory txBytes, uint pos) private pure returns (bytes32, bool, uint) { uint8 op; (op, pos) = getOpcode(txBytes, pos); //FIXME: Add support for uncompressed public keys require(op == 33, "Expected a compressed public key"); bytes32 pubKey; bool odd = txBytes[pos] == 0x03; pos += 1; assembly { pubKey := mload(add(add(txBytes, 0x20), pos)) } pos += 32; return (pubKey, odd, pos); } /** * Returns true if the tx output is an embedded ethereum address * @param txBytes Buffer where the entire transaction is stored. * @param pos Index into the tx buffer where the script is stored. * @param len Size of the script in terms of bytes. */ function isEthereumAddress(bytes memory txBytes, uint pos, uint len) private pure returns (bool) { // scriptPub format for the ethereum address is // 0x6a OP_RETURN // 0x14 PUSH20 // [] 20 bytes of the ethereum address return len == 20+2 && txBytes[pos] == bytes1(0x6a) && txBytes[pos+1] == bytes1(0x14); } // Read the ethereum address embedded in the tx output function readEthereumAddress(bytes memory txBytes, uint pos, uint) private pure returns (address) { uint256 data; assembly { data := mload(add(add(txBytes, 22), pos)) } return address(uint160(data)); } // Read next opcode from script function getOpcode(bytes memory txBytes, uint pos) private pure returns (uint8, uint) { return (uint8(txBytes[pos]), pos + 1); } function expmod(uint256 base, uint256 e, uint256 m) internal view returns (uint256 o) { assembly { // pointer to free memory let pos := mload(0x40) mstore(pos, 0x20) // Length of Base mstore(add(pos, 0x20), 0x20) // Length of Exponent mstore(add(pos, 0x40), 0x20) // Length of Modulus mstore(add(pos, 0x60), base) // Base mstore(add(pos, 0x80), e) // Exponent mstore(add(pos, 0xa0), m) // Modulus // call modexp precompile! if iszero(staticcall(gas(), 0x05, pos, 0xc0, pos, 0x20)) { revert(0, 0) } // data o := mload(pos) } } function pub2address(uint x, bool odd) internal view returns (address) { // First, uncompress pub key uint yy = mulmod(x, x, p); yy = mulmod(yy, x, p); yy = addmod(yy, 7, p); uint y = expmod(yy, q, p); if (((y & 1) == 1) != odd) { y = p - y; } require(yy == mulmod(y, y, p)); // Now, with uncompressed x and y, create the address return address(uint160(uint256(keccak256(abi.encodePacked(x, y))))); } // Gets the public key hash given a public key function pub2PubKeyHash(bytes32 pub, bool odd) internal pure returns (bytes20) { bytes1 firstByte = odd ? bytes1(0x03) : bytes1(0x02); return ripemd160(abi.encodePacked(sha256(abi.encodePacked(firstByte, pub)))); } // @dev - convert an unsigned integer from little-endian to big-endian representation // // @param _input - little-endian value // @return - input value in big-endian format function flip32Bytes(uint _input) internal pure returns (uint result) { assembly { let pos := mload(0x40) for { let i := 0 } lt(i, 32) { i := add(i, 1) } { mstore8(add(pos, i), byte(sub(31, i), _input)) } result := mload(pos) } } // helpers for flip32Bytes struct UintWrapper { uint value; } // @dev - Parses AuxPow part of block header // @param rawBytes - array of bytes with the block header // @param pos - starting position of the block header // @param uint - length of the block header // @return auxpow - AuxPoW struct with parsed data function parseAuxPoW(bytes memory rawBytes, uint pos, uint) internal view returns (AuxPoW memory auxpow) { // we need to traverse the bytes with a pointer because some fields are of variable length pos += 80; // skip non-AuxPoW header // auxpow.firstBytes = sliceBytes32Int(rawBytes, pos); uint slicePos; uint inputScriptPos; (slicePos, inputScriptPos) = getSlicePosAndScriptPos(rawBytes, pos); auxpow.txHash = dblShaFlipMem(rawBytes, pos, slicePos - pos); pos = slicePos; auxpow.scryptHash = sliceBytes32Int(rawBytes, pos); pos += 32; (auxpow.parentMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.coinbaseTxIndex = getBytesLE(rawBytes, pos, 32); pos += 4; (auxpow.chainMerkleProof, pos) = scanMerkleBranch(rawBytes, pos, 0); auxpow.dogeHashIndex = getBytesLE(rawBytes, pos, 32); pos += 40; // skip hash that was just read, parent version and prev block auxpow.parentMerkleRoot = sliceBytes32Int(rawBytes, pos); pos += 40; // skip root that was just read, parent block timestamp and bits auxpow.parentNonce = getBytesLE(rawBytes, pos, 32); uint coinbaseMerkleRootPosition; (auxpow.coinbaseMerkleRoot, coinbaseMerkleRootPosition, auxpow.coinbaseMerkleRootCode) = findCoinbaseMerkleRoot(rawBytes); if (coinbaseMerkleRootPosition - inputScriptPos > 20 && auxpow.coinbaseMerkleRootCode == 1) { // if it was found once and only once but not in the first 20 bytes, return this error code auxpow.coinbaseMerkleRootCode = ERR_NOT_IN_FIRST_20; } } // @dev - looks for {0xfa, 0xbe, 'm', 'm'} byte sequence // returns the following 32 bytes if it appears once and only once, // 0 otherwise // also returns the position where the bytes first appear function findCoinbaseMerkleRoot(bytes memory rawBytes) private pure returns (uint, uint, uint) { uint position; bool found = false; for (uint i = 0; i < rawBytes.length; ++i) { if (rawBytes[i] == 0xfa && rawBytes[i+1] == 0xbe && rawBytes[i+2] == 0x6d && rawBytes[i+3] == 0x6d) { if (found) { // found twice return (0, position - 4, ERR_FOUND_TWICE); } else { found = true; position = i + 4; } } } if (!found) { // no merge mining header return (0, position - 4, ERR_NO_MERGE_HEADER); } else { return (sliceBytes32Int(rawBytes, position), position - 4, 1); } } // @dev - Evaluate the merkle root // // Given an array of hashes it calculates the // root of the merkle tree. // // @return root of merkle tree function makeMerkle(bytes32[] calldata hashes2) external pure returns (bytes32) { bytes32[] memory hashes = hashes2; uint length = hashes.length; if (length == 1) return hashes[0]; require(length > 0); uint i; uint j; uint k; k = 0; while (length > 1) { k = 0; for (i = 0; i < length; i += 2) { j = i+1<length ? i+1 : length-1; hashes[k] = bytes32(concatHash(uint(hashes[i]), uint(hashes[j]))); k += 1; } length = k; } return hashes[0]; } // @dev - For a valid proof, returns the root of the Merkle tree. // // @param _txHash - transaction hash // @param _txIndex - transaction's index within the block it's assumed to be in // @param _siblings - transaction's Merkle siblings // @return - Merkle tree root of the block the transaction belongs to if the proof is valid, // garbage if it's invalid function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) internal pure returns (uint) { uint resultHash = _txHash; for (uint i = 0; i < _siblings.length; i++) { uint proofStep = _siblings[i]; uint left; uint right; // 0 means _siblings is on the right; 1 means left if (_txIndex % 2 == 1) { left = proofStep; right = resultHash; } else { left = resultHash; right = proofStep; } resultHash = concatHash(left, right); _txIndex /= 2; } return resultHash; } // @dev - calculates the Merkle root of a tree containing Litecoin transactions // in order to prove that `ap`'s coinbase tx is in that Litecoin block. // // @param _ap - AuxPoW information // @return - Merkle root of Litecoin block that the Dogecoin block // with this info was mined in if AuxPoW Merkle proof is correct, // garbage otherwise function computeParentMerkle(AuxPoW memory _ap) internal pure returns (uint) { return flip32Bytes(computeMerkle(_ap.txHash, _ap.coinbaseTxIndex, _ap.parentMerkleProof)); } // @dev - calculates the Merkle root of a tree containing auxiliary block hashes // in order to prove that the Dogecoin block identified by _blockHash // was merge-mined in a Litecoin block. // // @param _blockHash - SHA-256 hash of a certain Dogecoin block // @param _ap - AuxPoW information corresponding to said block // @return - Merkle root of auxiliary chain tree // if AuxPoW Merkle proof is correct, garbage otherwise function computeChainMerkle(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { return computeMerkle(_blockHash, _ap.dogeHashIndex, _ap.chainMerkleProof); } // @dev - Helper function for Merkle root calculation. // Given two sibling nodes in a Merkle tree, calculate their parent. // Concatenates hashes `_tx1` and `_tx2`, then hashes the result. // // @param _tx1 - Merkle node (either root or internal node) // @param _tx2 - Merkle node (either root or internal node), has to be `_tx1`'s sibling // @return - `_tx1` and `_tx2`'s parent, i.e. the result of concatenating them, // hashing that twice and flipping the bytes. function concatHash(uint _tx1, uint _tx2) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(flip32Bytes(_tx1), flip32Bytes(_tx2))))))); } // @dev - checks if a merge-mined block's Merkle proofs are correct, // i.e. Doge block hash is in coinbase Merkle tree // and coinbase transaction is in parent Merkle tree. // // @param _blockHash - SHA-256 hash of the block whose Merkle proofs are being checked // @param _ap - AuxPoW struct corresponding to the block // @return 1 if block was merge-mined and coinbase index, chain Merkle root and Merkle proofs are correct, // respective error code otherwise function checkAuxPoW(uint _blockHash, AuxPoW memory _ap) internal pure returns (uint) { if (_ap.coinbaseTxIndex != 0) { return ERR_COINBASE_INDEX; } if (_ap.coinbaseMerkleRootCode != 1) { return _ap.coinbaseMerkleRootCode; } if (computeChainMerkle(_blockHash, _ap) != _ap.coinbaseMerkleRoot) { return ERR_CHAIN_MERKLE; } if (computeParentMerkle(_ap) != _ap.parentMerkleRoot) { return ERR_PARENT_MERKLE; } return 1; } function sha256mem(bytes memory _rawBytes, uint offset, uint len) internal view returns (bytes32 result) { assembly { // Call sha256 precompiled contract (located in address 0x02) to copy data. // Assign to pos the next available memory position (stored in memory position 0x40). let pos := mload(0x40) if iszero(staticcall(gas(), 0x02, add(add(_rawBytes, 0x20), offset), len, pos, 0x20)) { revert(0, 0) } result := mload(pos) } } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlip(bytes memory _dataBytes) internal pure returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes)))))); } // @dev - Bitcoin-way of hashing // @param _dataBytes - raw data to be hashed // @return - result of applying SHA-256 twice to raw data and then flipping the bytes function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) internal view returns (uint) { return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len))))); } // @dev – Read a bytes32 from an offset in the byte array function readBytes32(bytes memory data, uint offset) internal pure returns (bytes32) { bytes32 result; assembly { result := mload(add(add(data, 0x20), offset)) } return result; } // @dev – Read an uint32 from an offset in the byte array function readUint32(bytes memory data, uint offset) internal pure returns (uint32) { uint32 result; assembly { let word := mload(add(add(data, 0x20), offset)) result := add(byte(3, word), add(mul(byte(2, word), 0x100), add(mul(byte(1, word), 0x10000), mul(byte(0, word), 0x1000000)))) } return result; } // @dev - Bitcoin-way of computing the target from the 'bits' field of a block header // based on http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html//ref3 // // @param _bits - difficulty in bits format // @return - difficulty in target format function targetFromBits(uint32 _bits) internal pure returns (uint) { uint exp = _bits / 0x1000000; // 2**24 uint mant = _bits & 0xffffff; return mant * 256**(exp - 3); } uint constant DOGECOIN_DIFFICULTY_ONE = 0xFFFFF * 256**(0x1e - 3); // @dev - Calculate dogecoin difficulty from target // https://en.bitcoin.it/wiki/Difficulty // Min difficulty for bitcoin is 0x1d00ffff // Min difficulty for dogecoin is 0x1e0fffff function targetToDiff(uint target) internal pure returns (uint) { return DOGECOIN_DIFFICULTY_ONE / target; } // @dev - Parse an array of bytes32 function parseBytes32Array(bytes calldata data) external pure returns (bytes32[] memory) { require(data.length % 32 == 0); uint count = data.length / 32; bytes32[] memory hashes = new bytes32[](count); for (uint i=0; i<count; ++i) { hashes[i] = readBytes32(data, 32*i); } return hashes; } // 0x00 version // 0x04 prev block hash // 0x24 merkle root // 0x44 timestamp // 0x48 bits // 0x4c nonce // @dev - extract version field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading version from // @return - block's version in big endian format function getVersion(bytes memory _blockHeader, uint pos) internal pure returns (uint32 version) { assembly { let word := mload(add(add(_blockHeader, 0x4), pos)) version := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - extract previous block field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading hash from // @return - hash of block's parent in big endian format function getHashPrevBlock(bytes memory _blockHeader, uint pos) internal pure returns (uint) { uint hashPrevBlock; assembly { hashPrevBlock := mload(add(add(_blockHeader, 0x24), pos)) } return flip32Bytes(hashPrevBlock); } // @dev - extract Merkle root field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading root from // @return - block's Merkle root in big endian format function getHeaderMerkleRoot(bytes memory _blockHeader, uint pos) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 0x44), pos)) } return flip32Bytes(merkle); } // @dev - extract bits field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading bits from // @return - block's difficulty in bits format, also big-endian function getBits(bytes memory _blockHeader, uint pos) internal pure returns (uint32 bits) { assembly { let word := mload(add(add(_blockHeader, 0x50), pos)) bits := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - extract timestamp field from a raw Dogecoin block header // // @param _blockHeader - Dogecoin block header bytes // @param pos - where to start reading bits from // @return - block's timestamp in big-endian format function getTimestamp(bytes memory _blockHeader, uint pos) internal pure returns (uint32 time) { assembly { let word := mload(add(add(_blockHeader, 0x4c), pos)) time := add(byte(24, word), add(mul(byte(25, word), 0x100), add(mul(byte(26, word), 0x10000), mul(byte(27, word), 0x1000000)))) } } // @dev - converts raw bytes representation of a Dogecoin block header to struct representation // // @param _rawBytes - first 80 bytes of a block header // @return - exact same header information in BlockHeader struct form function parseHeaderBytes(bytes memory _rawBytes, uint pos) internal view returns (BlockHeader memory bh) { bh.version = getVersion(_rawBytes, pos); bh.time = getTimestamp(_rawBytes, pos); bh.bits = getBits(_rawBytes, pos); bh.blockHash = dblShaFlipMem(_rawBytes, pos, 80); bh.prevBlock = getHashPrevBlock(_rawBytes, pos); bh.merkleRoot = getHeaderMerkleRoot(_rawBytes, pos); } uint32 constant VERSION_AUXPOW = (1 << 8); // @dev - Converts a bytes of size 4 to uint32, // e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304 function bytesToUint32Flipped(bytes memory input, uint pos) internal pure returns (uint32 result) { result = uint32(uint8(input[pos])) + uint32(uint8(input[pos + 1]))*(2**8) + uint32(uint8(input[pos + 2]))*(2**16) + uint32(uint8(input[pos + 3]))*(2**24); } // @dev - checks version to determine if a block has merge mining information function isMergeMined(bytes memory _rawBytes, uint pos) internal pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; } // @dev - checks version to determine if a block has merge mining information function isMergeMined(BlockHeader memory _blockHeader) internal pure returns (bool) { return _blockHeader.version & VERSION_AUXPOW != 0; } // @dev - Verify block header // @param _blockHeaderBytes - array of bytes with the block header // @param _pos - starting position of the block header // @param _len - length of the block header // @param _proposedBlockScryptHash - proposed block scrypt hash // @return - [ErrorCode, BlockSha256Hash, BlockScryptHash, IsMergeMined] function verifyBlockHeader(bytes calldata _blockHeaderBytes, uint _pos, uint _len, uint _proposedBlockScryptHash) external view returns (uint, uint, uint, bool) { BlockHeader memory blockHeader = parseHeaderBytes(_blockHeaderBytes, _pos); uint blockSha256Hash = blockHeader.blockHash; if (isMergeMined(blockHeader)) { AuxPoW memory ap = parseAuxPoW(_blockHeaderBytes, _pos, _len); if (flip32Bytes(ap.scryptHash) > targetFromBits(blockHeader.bits)) { return (ERR_PROOF_OF_WORK, blockHeader.blockHash, ap.scryptHash, true); } uint auxPoWCode = checkAuxPoW(blockSha256Hash, ap); if (auxPoWCode != 1) { return (auxPoWCode, blockHeader.blockHash, ap.scryptHash, true); } return (0, blockHeader.blockHash, ap.scryptHash, true); } else { if (flip32Bytes(_proposedBlockScryptHash) > targetFromBits(blockHeader.bits)) { return (ERR_PROOF_OF_WORK, blockHeader.blockHash, _proposedBlockScryptHash, false); } return (0, blockHeader.blockHash, _proposedBlockScryptHash, false); } } // @dev - Calculate difficulty from compact representation (bits) found in block function diffFromBits(uint32 bits) external pure returns (uint) { return targetToDiff(targetFromBits(bits)); } // For verifying Dogecoin difficulty uint constant DIFFICULTY_ADJUSTMENT_INTERVAL = 1; // Bitcoin adjusts every block uint constant TARGET_TIMESPAN = 60; // 1 minute uint constant TARGET_TIMESPAN_DIV_4 = TARGET_TIMESPAN / 4; uint constant TARGET_TIMESPAN_MUL_4 = TARGET_TIMESPAN * 4; uint constant UNROUNDED_MAX_TARGET = 2**224 - 1; // different from (2**16-1)*2**208 http =//bitcoin.stackexchange.com/questions/13803/how/ exactly-was-the-original-coefficient-for-difficulty-determined uint constant POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // @dev - Implementation of DigiShield, almost directly translated from // C++ implementation of Dogecoin. See function calculateDogecoinNextWorkRequired // on dogecoin/src/dogecoin.cpp for more details. // Calculates the next block's difficulty based on the current block's elapsed time // and the desired mining time for a block, which is 60 seconds after block 145k. // // @param _actualTimespan - time elapsed from previous block creation til current block creation; // i.e., how much time it took to mine the current block // @param _bits - previous block header difficulty (in bits) // @return - expected difficulty for the next block function calculateDigishieldDifficulty(int64 _actualTimespan, uint32 _bits) external pure returns (uint32 result) { int64 retargetTimespan = int64(TARGET_TIMESPAN); int64 nModulatedTimespan = int64(_actualTimespan); nModulatedTimespan = retargetTimespan + int64(nModulatedTimespan - retargetTimespan) / int64(8); //amplitude filter int64 nMinTimespan = retargetTimespan - (int64(retargetTimespan) / int64(4)); int64 nMaxTimespan = retargetTimespan + (int64(retargetTimespan) / int64(2)); // Limit adjustment step if (nModulatedTimespan < nMinTimespan) { nModulatedTimespan = nMinTimespan; } else if (nModulatedTimespan > nMaxTimespan) { nModulatedTimespan = nMaxTimespan; } // Retarget uint bnNew = targetFromBits(_bits); bnNew = bnNew * uint(nModulatedTimespan); bnNew = uint(bnNew) / uint(retargetTimespan); if (bnNew > POW_LIMIT) { bnNew = POW_LIMIT; } return toCompactBits(bnNew); } // @dev - shift information to the right by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the right, i.e. divided by 2**`_shift` function shiftRight(uint _val, uint _shift) private pure returns (uint) { return _val / uint(2)**_shift; } // @dev - shift information to the left by a specified number of bits // // @param _val - value to be shifted // @param _shift - number of bits to shift // @return - `_val` shifted `_shift` bits to the left, i.e. multiplied by 2**`_shift` function shiftLeft(uint _val, uint _shift) private pure returns (uint) { return _val * uint(2)**_shift; } // @dev - get the number of bits required to represent a given integer value without losing information // // @param _val - unsigned integer value // @return - given value's bit length function bitLen(uint _val) private pure returns (uint length) { uint int_type = _val; while (int_type > 0) { int_type = shiftRight(int_type, 1); length += 1; } } // @dev - Convert uint256 to compact encoding // based on https://github.com/petertodd/python-bitcoinlib/blob/2a5dda45b557515fb12a0a18e5dd48d2f5cd13c2/bitcoin/core/serialize.py // Analogous to arith_uint256::GetCompact from C++ implementation // // @param _val - difficulty in target format // @return - difficulty in bits format function toCompactBits(uint _val) private pure returns (uint32) { uint nbytes = uint (shiftRight((bitLen(_val) + 7), 3)); uint32 compact = 0; if (nbytes <= 3) { compact = uint32 (shiftLeft((_val & 0xFFFFFF), 8 * (3 - nbytes))); } else { compact = uint32 (shiftRight(_val, 8 * (nbytes - 3))); compact = uint32 (compact & 0xFFFFFF); } // If the sign bit (0x00800000) is set, divide the mantissa by 256 and // increase the exponent to get an encoding without it set. if ((compact & 0x00800000) > 0) { compact = uint32(shiftRight(compact, 8)); nbytes += 1; } return compact | uint32(shiftLeft(nbytes, 24)); } /** * Dead code. * This is currently unused code. This should be deleted once it is deemed no longer useful. */ // Check whether `btcAddress` is in the transaction outputs *and* // whether *at least* `value` has been sent to it. function checkValueSent(bytes memory txBytes, bytes20 btcAddress, uint value) private pure returns (bool) { uint pos = 4; // skip version pos = skipInputs(txBytes, pos); // find end of inputs // scan *all* the outputs and find where they are uint[] memory output_values; uint[] memory script_starts; uint[] memory output_script_lens; (output_values, script_starts, output_script_lens,) = scanOutputs(txBytes, pos, 0); // look at each output and check whether it at least value to btcAddress for (uint i = 0; i < output_values.length; i++) { bytes20 pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]); if (pkhash == btcAddress && output_values[i] >= value) { return true; } } return false; } // Get the pubkeyhash / scripthash from an output script. Assumes // pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs. // Returns the pubkeyhash/ scripthash, or zero if unknown output. function parseOutputScript(bytes memory txBytes, uint pos, uint script_len) private pure returns (bytes20) { if (isP2PKH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 3); } else if (isP2SH(txBytes, pos, script_len)) { return sliceBytes20(txBytes, pos + 2); } else { return bytes20(0); } } // returns true if the bytes located in txBytes by pos and // script_len represent a P2SH script function isP2SH(bytes memory txBytes, uint pos, uint script_len) private pure returns (bool) { return (script_len == 23) // 20 byte scripthash + 3 bytes of script && (txBytes[pos + 0] == 0xa9) // OP_HASH160 && (txBytes[pos + 1] == 0x14) // bytes to push && (txBytes[pos + 22] == 0x87); // OP_EQUAL } // scan the full transaction bytes and return the first two output // values (in satoshis) and addresses (in binary) function getFirstTwoOutputs(bytes memory txBytes) internal pure returns (uint, bytes20, uint, bytes20) { uint pos; uint[] memory output_script_lens; uint[] memory script_starts; uint[] memory output_values; bytes20[] memory output_public_key_hashes = new bytes20[](2); pos = 4; // skip version pos = skipInputs(txBytes, pos); (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2); for (uint i = 0; i < 2; i++) { bytes20 pkhash = parseP2PKHOutputScript(txBytes, script_starts[i], output_script_lens[i]); output_public_key_hashes[i] = pkhash; } return (output_values[0], output_public_key_hashes[0], output_values[1], output_public_key_hashes[1]); } function ptr(UintWrapper memory uw) private pure returns (uint addr) { assembly { addr := uw } } }
pointer to free memory call modexp precompile!
function expmod(uint256 base, uint256 e, uint256 m) internal view returns (uint256 o) { assembly { let pos := mload(0x40) if iszero(staticcall(gas(), 0x05, pos, 0xc0, pos, 0x20)) { revert(0, 0) } } }
12,605,607
[ 1, 10437, 358, 4843, 3778, 745, 1965, 23829, 675, 11100, 5, 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, 1329, 1711, 12, 11890, 5034, 1026, 16, 2254, 5034, 425, 16, 2254, 5034, 312, 13, 2713, 1476, 1135, 261, 11890, 5034, 320, 13, 288, 203, 3639, 19931, 288, 203, 5411, 2231, 949, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 309, 353, 7124, 12, 3845, 1991, 12, 31604, 9334, 374, 92, 6260, 16, 949, 16, 374, 6511, 20, 16, 949, 16, 374, 92, 3462, 3719, 288, 203, 7734, 15226, 12, 20, 16, 374, 13, 203, 5411, 289, 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, -100, -100, -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-09-07 */ // SPDX-License-Identifier: MIT /* solium-disable indentation */ pragma solidity 0.8.7; pragma abicoder v2; /* solium-disable error-reason */ library ECVerify { function ecverify(bytes32 hash, bytes memory signature) internal pure returns (address signature_address) { require(signature.length == 65); bytes32 r; bytes32 s; uint8 v; // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { // solium-disable-line security/no-inline-assembly r := mload(add(signature, 32)) s := mload(add(signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes following the signature. v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible if (v < 27) { v += 27; } require(v == 27 || v == 28); signature_address = ecrecover(hash, v, r, s); // ecrecover returns zero on error require(signature_address != address(0x0)); return signature_address; } } /* solium-disable error-reason */ library MessageType { enum MessageTypeId { None, BalanceProof, BalanceProofUpdate, Withdraw, CooperativeSettle, IOU, MSReward } } interface Token { /// @return supply total amount of tokens function totalSupply() external view returns (uint256 supply); /// @param _owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address _owner) external view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transfer(address _to, uint256 _value) external returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return success Whether the approval was successful or not function approve(address _spender, uint256 _value) external returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return remaining Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // Optionally implemented function to show the number of decimals for the token function decimals() external view returns (uint8 decimals); } /// @title Utils /// @notice Utils contract for various helpers used by the Raiden Network smart /// contracts. contract Utils { uint256 constant MAX_SAFE_UINT256 = 2**256 - 1; /// @notice Check if a contract exists /// @param contract_address The address to check whether a contract is /// deployed or not /// @return True if a contract exists, false otherwise function contractExists(address contract_address) public view returns (bool) { uint size; assembly { // solium-disable-line security/no-inline-assembly size := extcodesize(contract_address) } return size > 0; } string public constant signature_prefix = "\x19Ethereum Signed Message:\n"; function min(uint256 a, uint256 b) public pure returns (uint256) { return a > b ? b : a; } function max(uint256 a, uint256 b) public pure returns (uint256) { return a > b ? a : b; } /// @dev Special subtraction function that does not fail when underflowing. /// @param a Minuend /// @param b Subtrahend /// @return Minimum between the result of the subtraction and 0, the maximum /// subtrahend for which no underflow occurs function failsafe_subtract(uint256 a, uint256 b) public pure returns (uint256, uint256) { unchecked { return a > b ? (a - b, b) : (0, a); } } /// @dev Special addition function that does not fail when overflowing. /// @param a Addend /// @param b Addend /// @return Maximum between the result of the addition or the maximum /// uint256 value function failsafe_addition(uint256 a, uint256 b) public pure returns (uint256) { unchecked { uint256 sum = a + b; return sum >= a ? sum : MAX_SAFE_UINT256; } } } /// @title SecretRegistry /// @notice SecretRegistry contract for registering secrets from Raiden Network /// clients. contract SecretRegistry { // sha256(secret) => block number at which the secret was revealed mapping(bytes32 => uint256) private secrethash_to_block; event SecretRevealed(bytes32 indexed secrethash, bytes32 secret); /// @notice Registers a hash time lock secret and saves the block number. /// This allows the lock to be unlocked after the expiration block /// @param secret The secret used to lock the hash time lock /// @return true if secret was registered, false if the secret was already /// registered function registerSecret(bytes32 secret) public returns (bool) { bytes32 secrethash = sha256(abi.encodePacked(secret)); if (secrethash_to_block[secrethash] > 0) { return false; } secrethash_to_block[secrethash] = block.number; emit SecretRevealed(secrethash, secret); return true; } /// @notice Registers multiple hash time lock secrets and saves the block /// number /// @param secrets The array of secrets to be registered /// @return true if all secrets could be registered, false otherwise function registerSecretBatch(bytes32[] memory secrets) public returns (bool) { bool completeSuccess = true; for(uint i = 0; i < secrets.length; i++) { if(!registerSecret(secrets[i])) { completeSuccess = false; } } return completeSuccess; } /// @notice Get the stored block number at which the secret was revealed /// @param secrethash The hash of the registered secret `keccak256(secret)` /// @return The block number at which the secret was revealed function getSecretRevealBlockHeight(bytes32 secrethash) public view returns (uint256) { return secrethash_to_block[secrethash]; } } // MIT License // Copyright (c) 2018 // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. contract Controllable { address public controller; modifier onlyController() { require(msg.sender == controller, "Can only be called by controller"); _; } /// @notice Changes the controller who is allowed to deprecate or remove limits. /// Can only be called by the controller. function changeController(address new_controller) external onlyController { controller = new_controller; } } /// @title TokenNetwork /// @notice Stores and manages all the Raiden Network channels that use the /// token specified in this TokenNetwork contract. contract TokenNetwork is Utils, Controllable { // Instance of the token used by the channels Token public token; // Instance of SecretRegistry used for storing secrets revealed in a // mediating transfer. SecretRegistry public secret_registry; uint256 public settlement_timeout_min; uint256 public settlement_timeout_max; // The deposit limit per channel per participant. uint256 public channel_participant_deposit_limit; // The total combined deposit of all channels across the whole network uint256 public token_network_deposit_limit; // Global, monotonically increasing counter that keeps track of all the // opened channels in this contract uint256 public channel_counter; // Only for the limited Red Eyes release bool public safety_deprecation_switch = false; // channel_identifier => Channel // channel identifier is the channel_counter value at the time of opening // the channel mapping (uint256 => Channel) public channels; // This is needed to enforce one channel per pair of participants // The key is keccak256(participant1_address, participant2_address) mapping (bytes32 => uint256) public participants_hash_to_channel_identifier; // We keep the unlock data in a separate mapping to allow channel data // structures to be removed when settling uncooperatively. If there are // locked pending transfers, we need to store data needed to unlock them at // a later time. // The key is `keccak256(uint256 channel_identifier, address participant, // address partner)` Where `participant` is the participant that sent the // pending transfers We need `partner` for knowing where to send the // claimable tokens mapping(bytes32 => UnlockData) private unlock_identifier_to_unlock_data; struct Participant { // Total amount of tokens transferred to this smart contract through // the `setTotalDeposit` function, for a specific channel, in the // participant's benefit. // This is a strictly monotonic value. Note that direct token transfer // into the contract cannot be tracked and will be stuck. uint256 deposit; // Total amount of tokens withdrawn by the participant during the // lifecycle of this channel. // This is a strictly monotonic value. uint256 withdrawn_amount; // This is a value set to true after the channel has been closed, only // if this is the participant who closed the channel. bool is_the_closer; // keccak256 of the balance data provided after a closeChannel or an // updateNonClosingBalanceProof call bytes32 balance_hash; // Monotonically increasing counter of the off-chain transfers, // provided along with the balance_hash uint256 nonce; } enum ChannelState { NonExistent, // 0 Opened, // 1 Closed, // 2 Settled, // 3; Note: The channel has at least one pending unlock Removed // 4; Note: Channel data is removed, there are no pending unlocks } struct Channel { // After opening the channel this value represents the settlement // window. This is the number of blocks that need to be mined between // closing the channel uncooperatively and settling the channel. // After the channel has been uncooperatively closed, this value // represents the block number after which settleChannel can be called. uint256 settle_block_number; ChannelState state; mapping(address => Participant) participants; } struct WithdrawInput { address participant; uint256 total_withdraw; uint256 expiration_block; bytes participant_signature; bytes partner_signature; } struct SettlementData { uint256 deposit; uint256 withdrawn; uint256 transferred; uint256 locked; } struct UnlockData { // keccak256 hash of the pending locks from the Raiden client bytes32 locksroot; // Total amount of tokens locked in the pending locks corresponding // to the `locksroot` uint256 locked_amount; } struct SettleInput { address participant; uint256 transferred_amount; uint256 locked_amount; bytes32 locksroot; } event ChannelOpened( uint256 indexed channel_identifier, address indexed participant1, address indexed participant2, uint256 settle_timeout ); event ChannelNewDeposit( uint256 indexed channel_identifier, address indexed participant, uint256 total_deposit ); // Fires when the deprecation_switch's value changes event DeprecationSwitch(bool new_value); // total_withdraw is how much the participant has withdrawn during the // lifetime of the channel. The actual amount which the participant withdrew // is `total_withdraw - total_withdraw_from_previous_event_or_zero` event ChannelWithdraw( uint256 indexed channel_identifier, address indexed participant, uint256 total_withdraw ); event ChannelClosed( uint256 indexed channel_identifier, address indexed closing_participant, uint256 indexed nonce, bytes32 balance_hash ); event ChannelUnlocked( uint256 indexed channel_identifier, address indexed receiver, address indexed sender, bytes32 locksroot, uint256 unlocked_amount, uint256 returned_tokens ); event NonClosingBalanceProofUpdated( uint256 indexed channel_identifier, address indexed closing_participant, uint256 indexed nonce, bytes32 balance_hash ); event ChannelSettled( uint256 indexed channel_identifier, address participant1, uint256 participant1_amount, bytes32 participant1_locksroot, address participant2, uint256 participant2_amount, bytes32 participant2_locksroot ); modifier isSafe() { require(safety_deprecation_switch == false, "TN: network is deprecated"); _; } modifier isOpen(uint256 channel_identifier) { require(channels[channel_identifier].state == ChannelState.Opened, "TN: channel not open"); _; } modifier settleTimeoutValid(uint256 timeout) { require(timeout >= settlement_timeout_min, "TN: settle timeout < min"); require(timeout <= settlement_timeout_max, "TN: settle timeout > max"); _; } /// @param _token_address The address of the ERC20 token contract /// @param _secret_registry The address of SecretRegistry contract that witnesses the onchain secret reveals /// @param _settlement_timeout_min The shortest settlement period (in number of blocks) /// that can be chosen at the channel opening /// @param _settlement_timeout_max The longest settlement period (in number of blocks) /// that can be chosen at the channel opening /// @param _controller The Ethereum address that can disable new deposits and channel creation /// @param _channel_participant_deposit_limit The maximum amount of tokens that can be deposited by each /// participant of each channel. MAX_SAFE_UINT256 means no limits /// @param _token_network_deposit_limit The maximum amount of tokens that this contract can hold /// MAX_SAFE_UINT256 means no limits constructor( address _token_address, address _secret_registry, uint256 _settlement_timeout_min, uint256 _settlement_timeout_max, address _controller, uint256 _channel_participant_deposit_limit, uint256 _token_network_deposit_limit ) { require(_token_address != address(0x0), "TN: invalid token address"); require(_secret_registry != address(0x0), "TN: invalid SR address"); require(_controller != address(0x0), "TN: invalid controller address"); require(_settlement_timeout_min > 0, "TN: invalid settle timeout min"); require(_settlement_timeout_max > _settlement_timeout_min, "TN: invalid settle timeouts"); require(contractExists(_token_address), "TN: invalid token contract"); require(contractExists(_secret_registry), "TN: invalid SR contract"); require(_channel_participant_deposit_limit > 0, "TN: invalid participant limit"); require(_token_network_deposit_limit > 0, "TN: invalid network deposit limit"); require(_token_network_deposit_limit >= _channel_participant_deposit_limit, "TN: invalid deposit limits"); token = Token(_token_address); secret_registry = SecretRegistry(_secret_registry); settlement_timeout_min = _settlement_timeout_min; settlement_timeout_max = _settlement_timeout_max; // Make sure the contract is indeed a token contract require(token.totalSupply() > 0, "TN: no supply for token"); controller = _controller; channel_participant_deposit_limit = _channel_participant_deposit_limit; token_network_deposit_limit = _token_network_deposit_limit; } function deprecate() public isSafe onlyController { safety_deprecation_switch = true; emit DeprecationSwitch(safety_deprecation_switch); } /// @notice Opens a new channel between `participant1` and `participant2`. /// Can be called by anyone /// @param participant1 Ethereum address of a channel participant /// @param participant2 Ethereum address of the other channel participant /// @param settle_timeout Number of blocks that need to be mined between a /// call to closeChannel and settleChannel function openChannel(address participant1, address participant2, uint256 settle_timeout) public isSafe settleTimeoutValid(settle_timeout) returns (uint256) { bytes32 pair_hash; uint256 channel_identifier; // Red Eyes release token network limit require(token.balanceOf(address(this)) < token_network_deposit_limit, "TN/open: network deposit limit reached"); // First increment the counter // There will never be a channel with channel_identifier == 0 channel_counter += 1; channel_identifier = channel_counter; pair_hash = getParticipantsHash(participant1, participant2); // There must only be one channel opened between two participants at // any moment in time. require(participants_hash_to_channel_identifier[pair_hash] == 0, "TN/open: channel exists for participants"); participants_hash_to_channel_identifier[pair_hash] = channel_identifier; Channel storage channel = channels[channel_identifier]; // We always increase the channel counter, therefore no channel data can already exist, // corresponding to this channel_identifier. This check must never fail. assert(channel.settle_block_number == 0); assert(channel.state == ChannelState.NonExistent); // Store channel information channel.settle_block_number = settle_timeout; channel.state = ChannelState.Opened; emit ChannelOpened( channel_identifier, participant1, participant2, settle_timeout ); return channel_identifier; } /// @notice Opens a new channel between `participant1` and `participant2` /// and deposits for `participant1`. Can be called by anyone /// @param participant1 Ethereum address of a channel participant /// @param participant2 Ethereum address of the other channel participant /// @param settle_timeout Number of blocks that need to be mined between a /// call to closeChannel and settleChannel /// @param participant1_total_deposit The total amount of tokens that /// `participant1` will have as deposit function openChannelWithDeposit( address participant1, address participant2, uint256 settle_timeout, uint256 participant1_total_deposit ) public isSafe settleTimeoutValid(settle_timeout) returns (uint256) { uint256 channel_identifier; channel_identifier = openChannel(participant1, participant2, settle_timeout); setTotalDepositFor( channel_identifier, participant1, participant1_total_deposit, participant2, msg.sender ); return channel_identifier; } /// @notice Sets the channel participant total deposit value. /// Can be called by anyone. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param participant Channel participant whose deposit is being set /// @param total_deposit The total amount of tokens that the participant /// will have as a deposit /// @param partner Channel partner address, needed to compute the total /// channel deposit function setTotalDeposit( uint256 channel_identifier, address participant, uint256 total_deposit, address partner ) public isSafe isOpen(channel_identifier) { setTotalDepositFor( channel_identifier, participant, total_deposit, partner, msg.sender ); } /// @notice Allows `participant` to withdraw tokens from the channel that he /// has with `partner`, without closing it. Can be called by anyone. Can /// only be called once per each signed withdraw message /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param participant Channel participant, who will receive the withdrawn /// amount /// @param total_withdraw Total amount of tokens that are marked as /// withdrawn from the channel during the channel lifecycle /// @param participant_signature Participant's signature on the withdraw /// data /// @param partner_signature Partner's signature on the withdraw data function setTotalWithdraw( uint256 channel_identifier, address participant, uint256 total_withdraw, uint256 expiration_block, bytes calldata participant_signature, bytes calldata partner_signature ) external isOpen(channel_identifier) { this.setTotalWithdraw2( channel_identifier, WithdrawInput({ participant: participant, total_withdraw: total_withdraw, expiration_block: expiration_block, participant_signature: participant_signature, partner_signature: partner_signature }) ); } function setTotalWithdraw2( uint256 channel_identifier, WithdrawInput memory withdraw_data ) external isOpen(channel_identifier) { uint256 total_deposit; uint256 current_withdraw; address partner; require(withdraw_data.total_withdraw > 0, "TN/withdraw: total withdraw is zero"); require(block.number < withdraw_data.expiration_block, "TN/withdraw: expired"); // Authenticate both channel partners via their signatures. // `participant` is a part of the signed message, so given in the calldata. require(withdraw_data.participant == recoverAddressFromWithdrawMessage( channel_identifier, withdraw_data.participant, withdraw_data.total_withdraw, withdraw_data.expiration_block, withdraw_data.participant_signature ), "TN/withdraw: invalid participant sig"); partner = recoverAddressFromWithdrawMessage( channel_identifier, withdraw_data.participant, withdraw_data.total_withdraw, withdraw_data.expiration_block, withdraw_data.partner_signature ); // Validate that authenticated partners and the channel identifier match require( channel_identifier == getChannelIdentifier(withdraw_data.participant, partner), "TN/withdraw: channel id mismatch" ); // Read channel state after validating the function input Channel storage channel = channels[channel_identifier]; Participant storage participant_state = channel.participants[withdraw_data.participant]; Participant storage partner_state = channel.participants[partner]; total_deposit = participant_state.deposit + partner_state.deposit; // Entire withdrawn amount must not be bigger than the current channel deposit require( (withdraw_data.total_withdraw + partner_state.withdrawn_amount) <= total_deposit, "TN/withdraw: withdraw > deposit" ); require( withdraw_data.total_withdraw <= (withdraw_data.total_withdraw + partner_state.withdrawn_amount), "TN/withdraw: overflow" ); // Using the total_withdraw (monotonically increasing) in the signed // message ensures that we do not allow replay attack to happen, by // using the same withdraw proof twice. // Next two lines enforce the monotonicity of total_withdraw and check for an underflow: // (we use <= because current_withdraw == total_withdraw for the first withdraw) current_withdraw = withdraw_data.total_withdraw - participant_state.withdrawn_amount; require(current_withdraw <= withdraw_data.total_withdraw, "TN/withdraw: underflow"); // The actual amount of tokens that will be transferred must be > 0 to disable the reuse of // withdraw messages completely. require(current_withdraw > 0, "TN/withdraw: amount is zero"); // This should never fail at this point. Added check for security, because we directly set // the participant_state.withdrawn_amount = total_withdraw, // while we transfer `current_withdraw` tokens. assert(participant_state.withdrawn_amount + current_withdraw == withdraw_data.total_withdraw); emit ChannelWithdraw( channel_identifier, withdraw_data.participant, withdraw_data.total_withdraw ); // Do the state change and tokens transfer participant_state.withdrawn_amount = withdraw_data.total_withdraw; require(token.transfer(withdraw_data.participant, current_withdraw), "TN/withdraw: transfer failed"); // This should never happen, as we have an overflow check in setTotalDeposit assert(total_deposit >= participant_state.deposit); assert(total_deposit >= partner_state.deposit); // A withdraw should never happen if a participant already has a // balance proof in storage. This should never fail as we use isOpen. assert(participant_state.nonce == 0); assert(partner_state.nonce == 0); } /// @notice Cooperatively settles the balances between the two channel /// participants and transfers the agreed upon token amounts to the /// participants. After this the channel lifecycle has ended and no more /// operations can be done on it. /// An important constraint is that this function checks that all tokens /// in this channel are withdrawn. This means that the channel can *not* /// have any outstanding locked transfers. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param data1 Withdraw data of the first participant /// @param data2 Withdraw data of the second participant function cooperativeSettle( uint256 channel_identifier, WithdrawInput memory data1, WithdrawInput memory data2 ) external isOpen(channel_identifier) { uint256 total_deposit; // Validate that authenticated partners and the channel identifier match require( channel_identifier == getChannelIdentifier(data1.participant, data2.participant), "TN/coopSettle: channel id mismatch" ); Channel storage channel = channels[channel_identifier]; Participant storage participant1_state = channel.participants[data1.participant]; Participant storage participant2_state = channel.participants[data2.participant]; total_deposit = participant1_state.deposit + participant2_state.deposit; // The sum of the provided balances must be equal to the total // available deposit. This also implies that no locks must exist in the channel // when this is called, as otherwise the withdrawable amount would be smaller // than required. require((data1.total_withdraw + data2.total_withdraw) == total_deposit, "TN/coopSettle: incomplete amounts"); // Overflow check for the balances addition from the above check. // This overflow should never happen if the token.transfer function is implemented // correctly. We do not control the token implementation, therefore we add this // check for safety. require(data1.total_withdraw <= data1.total_withdraw + data2.total_withdraw, "TN/coopSettle: overflow"); if (data1.total_withdraw > 0) { this.setTotalWithdraw2( channel_identifier, data1 ); } if (data2.total_withdraw > 0) { this.setTotalWithdraw2( channel_identifier, data2 ); } removeChannelData(channel, channel_identifier, data1.participant, data2.participant); emit ChannelSettled( channel_identifier, data1.participant, data1.total_withdraw, 0, data2.participant, data2.total_withdraw, 0 ); } /// @notice Close the channel defined by the two participant addresses. /// Anybody can call this function on behalf of a participant (called /// the closing participant), providing a balance proof signed by /// both parties. Callable only once /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param closing_participant Channel participant who closes the channel /// @param non_closing_participant Channel partner of the `closing_participant`, /// who provided the balance proof /// @param balance_hash Hash of (transferred_amount, locked_amount, /// locksroot) /// @param additional_hash Computed from the message. Used for message /// authentication /// @param nonce Strictly monotonic value used to order transfers /// @param non_closing_signature Non-closing participant's signature of the balance proof data /// @param closing_signature Closing participant's signature of the balance /// proof data function closeChannel( uint256 channel_identifier, address non_closing_participant, address closing_participant, // The next four arguments form a balance proof. bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes memory non_closing_signature, bytes memory closing_signature ) public isOpen(channel_identifier) { require( channel_identifier == getChannelIdentifier(closing_participant, non_closing_participant), "TN/close: channel id mismatch" ); address recovered_non_closing_participant_address; Channel storage channel = channels[channel_identifier]; channel.state = ChannelState.Closed; channel.participants[closing_participant].is_the_closer = true; // This is the block number at which the channel can be settled. channel.settle_block_number += uint256(block.number); // The closing participant must have signed the balance proof. address recovered_closing_participant_address = recoverAddressFromBalanceProofCounterSignature( MessageType.MessageTypeId.BalanceProof, channel_identifier, balance_hash, nonce, additional_hash, non_closing_signature, closing_signature ); require(closing_participant == recovered_closing_participant_address, "TN/close: invalid closing sig"); // Nonce 0 means that the closer never received a transfer, therefore // never received a balance proof, or he is intentionally not providing // the latest transfer, in which case the closing party is going to // lose the tokens that were transferred to him. if (nonce > 0) { recovered_non_closing_participant_address = recoverAddressFromBalanceProof( channel_identifier, balance_hash, nonce, additional_hash, non_closing_signature ); // Signature must be from the channel partner require( non_closing_participant == recovered_non_closing_participant_address, "TN/close: invalid non-closing sig" ); updateBalanceProofData( channel, recovered_non_closing_participant_address, nonce, balance_hash ); } emit ChannelClosed(channel_identifier, closing_participant, nonce, balance_hash); } /// @notice Called on a closed channel, the function allows the non-closing /// participant to provide the last balance proof, which modifies the /// closing participant's state. Can be called multiple times by anyone. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param closing_participant Channel participant who closed the channel /// @param non_closing_participant Channel participant who needs to update /// the balance proof /// @param balance_hash Hash of (transferred_amount, locked_amount, /// locksroot) /// @param additional_hash Computed from the message. Used for message /// authentication /// @param nonce Strictly monotonic value used to order transfers /// @param closing_signature Closing participant's signature of the balance /// proof data /// @param non_closing_signature Non-closing participant signature of the /// balance proof data function updateNonClosingBalanceProof( uint256 channel_identifier, address closing_participant, address non_closing_participant, // The next four arguments form a balance proof bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes calldata closing_signature, bytes calldata non_closing_signature ) external { require( channel_identifier == getChannelIdentifier(closing_participant,non_closing_participant), "TN/update: channel id mismatch" ); require(balance_hash != bytes32(0x0), "TN/update: balance hash is zero"); require(nonce > 0, "TN/update: nonce is zero"); address recovered_non_closing_participant; address recovered_closing_participant; Channel storage channel = channels[channel_identifier]; require(channel.state == ChannelState.Closed, "TN/update: channel not closed"); // We need the signature from the non-closing participant to allow // anyone to make this transaction. E.g. a monitoring service. recovered_non_closing_participant = recoverAddressFromBalanceProofCounterSignature( MessageType.MessageTypeId.BalanceProofUpdate, channel_identifier, balance_hash, nonce, additional_hash, closing_signature, non_closing_signature ); require(non_closing_participant == recovered_non_closing_participant, "TN/update: invalid non-closing sig"); recovered_closing_participant = recoverAddressFromBalanceProof( channel_identifier, balance_hash, nonce, additional_hash, closing_signature ); require(closing_participant == recovered_closing_participant, "TN/update: invalid closing sig"); Participant storage closing_participant_state = channel.participants[closing_participant]; // Make sure the first signature is from the closing participant require(closing_participant_state.is_the_closer, "TN/update: incorrect signature order"); // Update the balance proof data for the closing_participant updateBalanceProofData(channel, closing_participant, nonce, balance_hash); emit NonClosingBalanceProofUpdated( channel_identifier, closing_participant, nonce, balance_hash ); } /// @notice Settles the balance between the two parties. Note that arguments /// order counts: `participant1_transferred_amount + /// participant1_locked_amount` <= `participant2_transferred_amount + /// participant2_locked_amount` /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param participant1 Channel participant /// @param participant1_transferred_amount The latest known amount of tokens /// transferred from `participant1` to `participant2` /// @param participant1_locked_amount Amount of tokens owed by /// `participant1` to `participant2`, contained in locked transfers that /// will be retrieved by calling `unlock` after the channel is settled /// @param participant1_locksroot The latest known hash of the /// pending hash-time locks of `participant1`, used to validate the unlocked /// proofs. If no balance_hash has been submitted, locksroot is ignored /// @param participant2 Other channel participant /// @param participant2_transferred_amount The latest known amount of tokens /// transferred from `participant2` to `participant1` /// @param participant2_locked_amount Amount of tokens owed by /// `participant2` to `participant1`, contained in locked transfers that /// will be retrieved by calling `unlock` after the channel is settled /// @param participant2_locksroot The latest known hash of the /// pending hash-time locks of `participant2`, used to validate the unlocked /// proofs. If no balance_hash has been submitted, locksroot is ignored function settleChannel( uint256 channel_identifier, address participant1, uint256 participant1_transferred_amount, uint256 participant1_locked_amount, bytes32 participant1_locksroot, address participant2, uint256 participant2_transferred_amount, uint256 participant2_locked_amount, bytes32 participant2_locksroot ) public { settleChannel2( channel_identifier, SettleInput({ participant: participant1, transferred_amount: participant1_transferred_amount, locked_amount: participant1_locked_amount, locksroot: participant1_locksroot }), SettleInput({ participant: participant2, transferred_amount: participant2_transferred_amount, locked_amount: participant2_locked_amount, locksroot: participant2_locksroot }) ); } function settleChannel2( uint256 channel_identifier, SettleInput memory participant1_settlement, SettleInput memory participant2_settlement ) public { // There are several requirements that this function MUST enforce: // - it MUST never fail; therefore, any overflows or underflows must be // handled gracefully // - it MUST ensure that if participants use the latest valid balance proofs, // provided by the official Raiden client, the participants will be able // to receive correct final balances at the end of the channel lifecycle // - it MUST ensure that the participants cannot cheat by providing an // old, valid balance proof of their partner; meaning that their partner MUST // receive at least the amount of tokens that he would have received if // the latest valid balance proofs are used. // - the contract cannot determine if a balance proof is invalid (values // are not within the constraints enforced by the official Raiden client), // therefore it cannot ensure correctness. Users MUST use the official // Raiden clients for signing balance proofs. address participant1 = participant1_settlement.participant; address participant2 = participant2_settlement.participant; require( channel_identifier == getChannelIdentifier(participant1, participant2), "TN/settle: channel id mismatch" ); Channel storage channel = channels[channel_identifier]; require(channel.state == ChannelState.Closed, "TN/settle: channel not closed"); // Settlement window must be over require(channel.settle_block_number < block.number, "TN/settle: settlement timeout"); Participant storage participant1_state = channel.participants[participant1]; Participant storage participant2_state = channel.participants[participant2]; require( verifyBalanceHashData(participant1_state, participant1_settlement), "TN/settle: invalid data for participant 1" ); require( verifyBalanceHashData(participant2_state, participant2_settlement), "TN/settle: invalid data for participant 2" ); // We are calculating the final token amounts that need to be // transferred to the participants now and the amount of tokens that // need to remain locked in the contract. These tokens can be unlocked // by calling `unlock`. // participant1_transferred_amount = the amount of tokens that // participant1 will receive in this transaction. // participant2_transferred_amount = the amount of tokens that // participant2 will receive in this transaction. // participant1_locked_amount = the amount of tokens remaining in the // contract, representing pending transfers from participant1 to participant2. // participant2_locked_amount = the amount of tokens remaining in the // contract, representing pending transfers from participant2 to participant1. // We are reusing variables due to the local variables number limit. // For better readability this can be refactored further. ( participant1_settlement.transferred_amount, participant2_settlement.transferred_amount, participant1_settlement.locked_amount, participant2_settlement.locked_amount ) = getSettleTransferAmounts( participant1_state, participant1_settlement.transferred_amount, participant1_settlement.locked_amount, participant2_state, participant2_settlement.transferred_amount, participant2_settlement.locked_amount ); removeChannelData(channel, channel_identifier, participant1, participant2); // Store balance data needed for `unlock`, including the calculated // locked amounts remaining in the contract. storeUnlockData( channel_identifier, participant1_settlement, participant2 ); storeUnlockData( channel_identifier, participant2_settlement, participant1 ); emit ChannelSettled( channel_identifier, participant1, participant1_settlement.transferred_amount, participant1_settlement.locksroot, participant2, participant2_settlement.transferred_amount, participant2_settlement.locksroot ); // Do the actual token transfers if (participant1_settlement.transferred_amount > 0) { require( token.transfer(participant1, participant1_settlement.transferred_amount), "TN/settle: transfer for participant 1 failed" ); } if (participant2_settlement.transferred_amount > 0) { require( token.transfer(participant2, participant2_settlement.transferred_amount), "TN/settle: transfer for participant 2 failed" ); } } /// @notice Unlocks all pending off-chain transfers from `sender` to /// `receiver` and sends the locked tokens corresponding to locks with /// secrets registered on-chain to the `receiver`. Locked tokens /// corresponding to locks where the secret was not revealed on-chain will /// return to the `sender`. Anyone can call unlock. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param receiver Address who will receive the claimable unlocked /// tokens /// @param sender Address who sent the pending transfers and will receive /// the unclaimable unlocked tokens /// @param locks All pending locks concatenated in order of creation /// that `sender` sent to `receiver` function unlock( uint256 channel_identifier, address receiver, address sender, bytes memory locks ) public { // Channel represented by channel_identifier must be settled and // channel data deleted require( channel_identifier != getChannelIdentifier(receiver, sender), "TN/unlock: channel id still exists" ); // After the channel is settled the storage is cleared, therefore the // value will be NonExistent and not Settled. The value Settled is used // for the external APIs require( channels[channel_identifier].state == ChannelState.NonExistent, "TN/unlock: channel not settled" ); bytes32 unlock_key; bytes32 computed_locksroot; uint256 unlocked_amount; uint256 locked_amount; uint256 returned_tokens; // Calculate the locksroot for the pending transfers and the amount of // tokens corresponding to the locked transfers with secrets revealed // on chain. (computed_locksroot, unlocked_amount) = getHashAndUnlockedAmount( locks ); // The sender must have a non-empty locksroot on-chain that must be // the same as the computed locksroot. // Get the amount of tokens that have been left in the contract, to // account for the pending transfers `sender` -> `receiver`. unlock_key = getUnlockIdentifier(channel_identifier, sender, receiver); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[unlock_key]; locked_amount = unlock_data.locked_amount; // Locksroot must be the same as the computed locksroot require(unlock_data.locksroot == computed_locksroot, "TN/unlock: locksroot mismatch"); // There are no pending transfers if the locked_amount is 0. // Transaction must fail require(locked_amount > 0, "TN/unlock: zero locked amount"); // Make sure we don't transfer more tokens than previously reserved in // the smart contract. unlocked_amount = min(unlocked_amount, locked_amount); // Transfer the rest of the tokens back to the sender returned_tokens = locked_amount - unlocked_amount; // Remove sender's unlock data delete unlock_identifier_to_unlock_data[unlock_key]; emit ChannelUnlocked( channel_identifier, receiver, sender, computed_locksroot, unlocked_amount, returned_tokens ); // Transfer the unlocked tokens to the receiver. unlocked_amount can // be 0 if (unlocked_amount > 0) { require(token.transfer(receiver, unlocked_amount), "TN/unlock: unlocked transfer failed"); } // Transfer the rest of the tokens back to the sender if (returned_tokens > 0) { require(token.transfer(sender, returned_tokens), "TN/unlock: returned transfer failed"); } // At this point, this should always be true assert(locked_amount >= returned_tokens); assert(locked_amount >= unlocked_amount); } /// @notice Returns the unique identifier for the channel given by the /// contract /// @param participant Address of a channel participant /// @param partner Address of the other channel participant /// @return Unique identifier for the channel. It can be 0 if channel does /// not exist function getChannelIdentifier(address participant, address partner) public view returns (uint256) { require(participant != address(0x0), "TN: participant address zero"); require(partner != address(0x0), "TN: partner address zero"); require(participant != partner, "TN: identical addresses"); bytes32 pair_hash = getParticipantsHash(participant, partner); return participants_hash_to_channel_identifier[pair_hash]; } /// @dev Returns the channel specific data. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param participant1 Address of a channel participant /// @param participant2 Address of the other channel participant /// @return Channel settle_block_number and state /// @notice The contract cannot really distinguish Settled and Removed /// states, especially when wrong participants are given as input. /// The contract does not remember the participants of the channel function getChannelInfo( uint256 channel_identifier, address participant1, address participant2 ) external view returns (uint256, ChannelState) { bytes32 unlock_key1; bytes32 unlock_key2; Channel storage channel = channels[channel_identifier]; ChannelState state = channel.state; // This must **not** update the storage if (state == ChannelState.NonExistent && channel_identifier > 0 && channel_identifier <= channel_counter ) { // The channel has been settled, channel data is removed Therefore, // the channel state in storage is actually `0`, or `NonExistent` // However, for this view function, we return `Settled`, in order // to provide a consistent external API state = ChannelState.Settled; // We might still have data stored for future unlock operations // Only if we do not, we can consider the channel as `Removed` unlock_key1 = getUnlockIdentifier(channel_identifier, participant1, participant2); UnlockData storage unlock_data1 = unlock_identifier_to_unlock_data[unlock_key1]; unlock_key2 = getUnlockIdentifier(channel_identifier, participant2, participant1); UnlockData storage unlock_data2 = unlock_identifier_to_unlock_data[unlock_key2]; if (unlock_data1.locked_amount == 0 && unlock_data2.locked_amount == 0) { state = ChannelState.Removed; } } return ( channel.settle_block_number, state ); } /// @dev Returns the channel specific data. /// @param channel_identifier Identifier for the channel on which this /// operation takes place /// @param participant Address of the channel participant whose data will be /// returned /// @param partner Address of the channel partner /// @return Participant's deposit, withdrawn_amount, whether the participant /// has called `closeChannel` or not, balance_hash, nonce, locksroot, /// locked_amount function getChannelParticipantInfo( uint256 channel_identifier, address participant, address partner ) external view returns (uint256, uint256, bool, bytes32, uint256, bytes32, uint256) { bytes32 unlock_key; Participant storage participant_state = channels[channel_identifier].participants[ participant ]; unlock_key = getUnlockIdentifier(channel_identifier, participant, partner); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[unlock_key]; return ( participant_state.deposit, participant_state.withdrawn_amount, participant_state.is_the_closer, participant_state.balance_hash, participant_state.nonce, unlock_data.locksroot, unlock_data.locked_amount ); } /// @dev Get the hash of the participant addresses, ordered /// lexicographically /// @param participant Address of a channel participant /// @param partner Address of the other channel participant function getParticipantsHash(address participant, address partner) public pure returns (bytes32) { require(participant != address(0x0), "TN: participant address zero"); require(partner != address(0x0), "TN: partner address zero"); require(participant != partner, "TN: identical addresses"); if (participant < partner) { return keccak256(abi.encodePacked(participant, partner)); } else { return keccak256(abi.encodePacked(partner, participant)); } } /// @dev Get the hash of the channel identifier and the participant /// addresses (whose ordering matters). The hash might be useful for /// the receiver to look up the appropriate UnlockData to claim /// @param channel_identifier Identifier for the channel which the /// UnlockData is about /// @param sender Sender of the pending transfers that the UnlockData /// represents /// @param receiver Receiver of the pending transfers that the UnlockData /// represents function getUnlockIdentifier( uint256 channel_identifier, address sender, address receiver ) public pure returns (bytes32) { require(sender != receiver, "TN: sender/receiver mismatch"); return keccak256(abi.encodePacked(channel_identifier, sender, receiver)); } function setTotalDepositFor( uint256 channel_identifier, address participant, uint256 total_deposit, address partner, address token_owner ) internal { require(channel_identifier == getChannelIdentifier(participant, partner), "TN/deposit: channel id mismatch"); require(total_deposit > 0, "TN/deposit: total_deposit is zero"); require(total_deposit <= channel_participant_deposit_limit, "TN/deposit: deposit limit reached"); uint256 added_deposit; uint256 channel_deposit; Channel storage channel = channels[channel_identifier]; Participant storage participant_state = channel.participants[participant]; Participant storage partner_state = channel.participants[partner]; unchecked { // Calculate the actual amount of tokens that will be transferred added_deposit = total_deposit - participant_state.deposit; // The actual amount of tokens that will be transferred must be > 0 require(added_deposit > 0, "TN/deposit: no deposit added"); // Underflow check; we use <= because added_deposit == total_deposit for the first deposit require(added_deposit <= total_deposit, "TN/deposit: deposit underflow"); // This should never fail at this point. Added check for security, because we directly set // the participant_state.deposit = total_deposit, while we transfer `added_deposit` tokens assert(participant_state.deposit + added_deposit == total_deposit); // Red Eyes release token network limit require( token.balanceOf(address(this)) + added_deposit <= token_network_deposit_limit, "TN/deposit: network limit reached" ); // Update the participant's channel deposit participant_state.deposit = total_deposit; // Calculate the entire channel deposit, to avoid overflow channel_deposit = participant_state.deposit + partner_state.deposit; // Overflow check require(channel_deposit >= participant_state.deposit, "TN/deposit: deposit overflow"); } emit ChannelNewDeposit( channel_identifier, participant, participant_state.deposit ); // Do the transfer require(token.transferFrom(token_owner, address(this), added_deposit), "TN/deposit: transfer failed"); } function updateBalanceProofData( Channel storage channel, address participant, uint256 nonce, bytes32 balance_hash ) internal { Participant storage participant_state = channel.participants[participant]; // Multiple calls to updateNonClosingBalanceProof can be made and we // need to store the last known balance proof data. // This line prevents Monitoring Services from getting rewards // again and again using the same reward proof. require(nonce > participant_state.nonce, "TN: nonce reused"); participant_state.nonce = nonce; participant_state.balance_hash = balance_hash; } function storeUnlockData( uint256 channel_identifier, SettleInput memory settle_input, address receiver ) internal { // If there are transfers to unlock, store the locksroot and total // amount of tokens if (settle_input.locked_amount == 0) { return; } bytes32 key = getUnlockIdentifier(channel_identifier, settle_input.participant, receiver); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[key]; unlock_data.locksroot = settle_input.locksroot; unlock_data.locked_amount = settle_input.locked_amount; } function getChannelAvailableDeposit( Participant storage participant1_state, Participant storage participant2_state ) internal view returns (uint256 total_available_deposit) { total_available_deposit = ( participant1_state.deposit + participant2_state.deposit - participant1_state.withdrawn_amount - participant2_state.withdrawn_amount ); } /// @dev Function that calculates the amount of tokens that the participants /// will receive when calling settleChannel. /// Check https://github.com/raiden-network/raiden-contracts/issues/188 for the settlement /// algorithm analysis and explanations. function getSettleTransferAmounts( Participant storage participant1_state, uint256 participant1_transferred_amount, uint256 participant1_locked_amount, Participant storage participant2_state, uint256 participant2_transferred_amount, uint256 participant2_locked_amount ) private view returns (uint256, uint256, uint256, uint256) { // The scope of this function is to compute the settlement amounts that // the two channel participants will receive when calling settleChannel // and the locked amounts that remain in the contract, to account for // the pending, not finalized transfers, that will be received by the // participants when calling `unlock`. // The amount of tokens that participant1 MUST receive at the end of // the channel lifecycle (after settleChannel and unlock) is: // B1 = D1 - W1 + T2 - T1 + Lc2 - Lc1 // The amount of tokens that participant2 MUST receive at the end of // the channel lifecycle (after settleChannel and unlock) is: // B2 = D2 - W2 + T1 - T2 + Lc1 - Lc2 // B1 + B2 = TAD = D1 + D2 - W1 - W2 // TAD = total available deposit at settlement time // L1 = Lc1 + Lu1 // L2 = Lc2 + Lu2 // where: // B1 = final balance of participant1 after the channel is removed // D1 = total amount deposited by participant1 into the channel // W1 = total amount withdrawn by participant1 from the channel // T2 = total amount transferred by participant2 to participant1 (finalized transfers) // T1 = total amount transferred by participant1 to participant2 (finalized transfers) // L1 = total amount of tokens locked in pending transfers, sent by // participant1 to participant2 // L2 = total amount of tokens locked in pending transfers, sent by // participant2 to participant1 // Lc2 = the amount that can be claimed by participant1 from the pending // transfers (that have not been finalized off-chain), sent by // participant2 to participant1. These are part of the locked amount // value from participant2's balance proof. They are considered claimed // if the secret corresponding to these locked transfers was registered // on-chain, in the SecretRegistry contract, before the lock's expiration. // Lu1 = unclaimable locked amount from L1 // Lc1 = the amount that can be claimed by participant2 from the pending // transfers (that have not been finalized off-chain), // sent by participant1 to participant2 // Lu2 = unclaimable locked amount from L2 // Notes: // 1) The unclaimble tokens from a locked amount will return to the sender. // At the time of calling settleChannel, the TokenNetwork contract does // not know what locked amounts are claimable or unclaimable. // 2) There are some Solidity constraints that make the calculations // more difficult: attention to overflows and underflows, that MUST be // handled without throwing. // Cases that require attention: // case1. If participant1 does NOT provide a balance proof or provides // an old balance proof. participant2_transferred_amount can be [0, // real_participant2_transferred_amount) We MUST NOT punish // participant2. // case2. If participant2 does NOT provide a balance proof or provides // an old balance proof. participant1_transferred_amount can be [0, // real_participant1_transferred_amount) We MUST NOT punish // participant1. // case3. If neither participants provide a balance proof, we just // subtract their withdrawn amounts from their deposits. // This is why, the algorithm implemented in Solidity is: // (explained at each step, below) // RmaxP1 = (T2 + L2) - (T1 + L1) + D1 - W1 // RmaxP1 = min(TAD, RmaxP1) // RmaxP2 = TAD - RmaxP1 // SL2 = min(RmaxP1, L2) // S1 = RmaxP1 - SL2 // SL1 = min(RmaxP2, L1) // S2 = RmaxP2 - SL1 // where: // RmaxP1 = due to possible over/underflows that only appear when using // old balance proofs & the fact that settlement balance calculation // is symmetric (we can calculate either RmaxP1 and RmaxP2 first, // order does not affect result), this is a convention used to determine // the maximum receivable amount of participant1 at settlement time // S1 = amount received by participant1 when calling settleChannel // SL1 = the maximum amount from L1 that can be locked in the // TokenNetwork contract when calling settleChannel (due to overflows // that only happen when using old balance proofs) // S2 = amount received by participant2 when calling settleChannel // SL2 = the maximum amount from L2 that can be locked in the // TokenNetwork contract when calling settleChannel (due to overflows // that only happen when using old balance proofs) uint256 participant1_amount; uint256 participant2_amount; uint256 total_available_deposit; SettlementData memory participant1_settlement; SettlementData memory participant2_settlement; participant1_settlement.deposit = participant1_state.deposit; participant1_settlement.withdrawn = participant1_state.withdrawn_amount; participant1_settlement.transferred = participant1_transferred_amount; participant1_settlement.locked = participant1_locked_amount; participant2_settlement.deposit = participant2_state.deposit; participant2_settlement.withdrawn = participant2_state.withdrawn_amount; participant2_settlement.transferred = participant2_transferred_amount; participant2_settlement.locked = participant2_locked_amount; // TAD = D1 + D2 - W1 - W2 = total available deposit at settlement time total_available_deposit = getChannelAvailableDeposit( participant1_state, participant2_state ); // RmaxP1 = (T2 + L2) - (T1 + L1) + D1 - W1 // This amount is the maximum possible amount that participant1 can // receive at settlement time and also contains the entire locked amount // of the pending transfers from participant2 to participant1. participant1_amount = getMaxPossibleReceivableAmount( participant1_settlement.deposit, participant1_settlement.withdrawn, participant1_settlement.transferred, participant1_settlement.locked, participant2_settlement.transferred, participant2_settlement.locked ); // RmaxP1 = min(TAD, RmaxP1) // We need to bound this to the available channel deposit in order to // not send tokens from other channels. The only case where TAD is // smaller than RmaxP1 is when at least one balance proof is old. participant1_amount = min(participant1_amount, total_available_deposit); // RmaxP2 = TAD - RmaxP1 // Now it is safe to subtract without underflow participant2_amount = total_available_deposit - participant1_amount; // SL2 = min(RmaxP1, L2) // S1 = RmaxP1 - SL2 // Both operations are done by failsafe_subtract // We take out participant2's pending transfers locked amount, bounding // it by the maximum receivable amount of participant1 (participant1_amount, participant2_locked_amount) = failsafe_subtract( participant1_amount, participant2_locked_amount ); // SL1 = min(RmaxP2, L1) // S2 = RmaxP2 - SL1 // Both operations are done by failsafe_subtract // We take out participant1's pending transfers locked amount, bounding // it by the maximum receivable amount of participant2 (participant2_amount, participant1_locked_amount) = failsafe_subtract( participant2_amount, participant1_locked_amount ); // This should never throw: // S1 and S2 MUST be smaller than TAD assert(participant1_amount <= total_available_deposit); assert(participant2_amount <= total_available_deposit); // S1 + S2 + SL1 + SL2 == TAD assert(total_available_deposit == ( participant1_amount + participant2_amount + participant1_locked_amount + participant2_locked_amount )); return ( participant1_amount, participant2_amount, participant1_locked_amount, participant2_locked_amount ); } function verifyBalanceHashData( Participant storage participant, SettleInput memory settle_input ) internal view returns (bool) { // When no balance proof has been provided, we need to check this // separately because hashing values of 0 outputs a value != 0 if (participant.balance_hash == 0 && settle_input.transferred_amount == 0 && settle_input.locked_amount == 0 /* locksroot is ignored. */ ) { return true; } // Make sure the hash of the provided state is the same as the stored // balance_hash return participant.balance_hash == keccak256(abi.encodePacked( settle_input.transferred_amount, settle_input.locked_amount, settle_input.locksroot )); } /// @dev Calculates the hash of the pending transfers data and /// calculates the amount of tokens that can be unlocked because the secret /// was registered on-chain. function getHashAndUnlockedAmount(bytes memory locks) internal view returns (bytes32, uint256) { uint256 length = locks.length; // each lock has this form: // (locked_amount || expiration_block || secrethash) = 3 * 32 bytes require(length % 96 == 0, "TN: invalid locks size"); uint256 i; uint256 total_unlocked_amount; uint256 unlocked_amount; bytes32 total_hash; for (i = 32; i < length; i += 96) { unlocked_amount = getLockedAmountFromLock(locks, i); total_unlocked_amount += unlocked_amount; } total_hash = keccak256(locks); return (total_hash, total_unlocked_amount); } function getLockedAmountFromLock(bytes memory locks, uint256 offset) internal view returns (uint256) { uint256 expiration_block; uint256 locked_amount; uint256 reveal_block; bytes32 secrethash; if (locks.length <= offset) { return 0; } assembly { // solium-disable-line security/no-inline-assembly expiration_block := mload(add(locks, offset)) locked_amount := mload(add(locks, add(offset, 32))) secrethash := mload(add(locks, add(offset, 64))) } // Check if the lock's secret was revealed in the SecretRegistry The // secret must have been revealed in the SecretRegistry contract before // the lock's expiration_block in order for the hash time lock transfer // to be successful. reveal_block = secret_registry.getSecretRevealBlockHeight(secrethash); if (reveal_block == 0 || expiration_block <= reveal_block) { locked_amount = 0; } return locked_amount; } function removeChannelData(Channel storage channel, uint256 channel_identifier, address participant1, address participant2) internal { bytes32 pair_hash; // Remove channel data from storage delete channel.participants[participant1]; delete channel.participants[participant2]; delete channels[channel_identifier]; // Remove the pair's channel counter pair_hash = getParticipantsHash(participant1, participant2); delete participants_hash_to_channel_identifier[pair_hash]; } function recoverAddressFromBalanceProof( uint256 channel_identifier, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes memory signature ) internal view returns (address signature_address) { // Length of the actual message: 20 + 32 + 32 + 32 + 32 + 32 + 32 string memory message_length = "212"; bytes32 message_hash = keccak256(abi.encodePacked( signature_prefix, message_length, address(this), block.chainid, uint256(MessageType.MessageTypeId.BalanceProof), channel_identifier, balance_hash, nonce, additional_hash )); signature_address = ECVerify.ecverify(message_hash, signature); } function recoverAddressFromBalanceProofCounterSignature( MessageType.MessageTypeId message_type_id, uint256 channel_identifier, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes memory closing_signature, bytes memory non_closing_signature ) internal view returns (address signature_address) { // Length of the actual message: 20 + 32 + 32 + 32 + 32 + 32 + 32 + 65 string memory message_prefix = "\x19Ethereum Signed Message:\n277"; bytes32 message_hash = keccak256(abi.encodePacked( message_prefix, address(this), block.chainid, uint256(message_type_id), channel_identifier, balance_hash, nonce, additional_hash, closing_signature )); signature_address = ECVerify.ecverify(message_hash, non_closing_signature); } function recoverAddressFromWithdrawMessage( uint256 channel_identifier, address participant, uint256 total_withdraw, uint256 expiration_block, bytes memory signature ) internal view returns (address signature_address) { // Length of the actual message: 20 + 32 + 32 + 32 + 20 + 32 + 32 string memory message_length = "200"; bytes32 message_hash = keccak256(abi.encodePacked( signature_prefix, message_length, address(this), block.chainid, uint256(MessageType.MessageTypeId.Withdraw), channel_identifier, participant, total_withdraw, expiration_block )); signature_address = ECVerify.ecverify(message_hash, signature); } function getMaxPossibleReceivableAmount( uint256 participant1_deposit, uint256 participant1_withdrawn, uint256 participant1_transferred, uint256 participant1_locked, uint256 participant2_transferred, uint256 participant2_locked ) public pure returns (uint256) { uint256 participant1_max_transferred; uint256 participant2_max_transferred; uint256 participant1_net_max_received; uint256 participant1_max_amount; // This is the maximum possible amount that participant1 could transfer // to participant2, if all the pending lock secrets have been // registered participant1_max_transferred = failsafe_addition( participant1_transferred, participant1_locked ); // This is the maximum possible amount that participant2 could transfer // to participant1, if all the pending lock secrets have been // registered participant2_max_transferred = failsafe_addition( participant2_transferred, participant2_locked ); // We enforce this check artificially, in order to get rid of hard // to deal with over/underflows. Settlement balance calculation is // symmetric (we can calculate either RmaxP1 and RmaxP2 first, order does // not affect result). This means settleChannel must be called with // ordered values. require(participant2_max_transferred >= participant1_max_transferred, "TN: transfers not ordered"); assert(participant1_max_transferred >= participant1_transferred); assert(participant2_max_transferred >= participant2_transferred); // This is the maximum amount that participant1 can receive at settlement time participant1_net_max_received = ( participant2_max_transferred - participant1_max_transferred ); // Next, we add the participant1's deposit and subtract the already // withdrawn amount participant1_max_amount = failsafe_addition( participant1_net_max_received, participant1_deposit ); // Subtract already withdrawn amount (participant1_max_amount, ) = failsafe_subtract( participant1_max_amount, participant1_withdrawn ); return participant1_max_amount; } /// @notice Removes the balance limits. /// Can only be called by the controller. function removeLimits() external onlyController { channel_participant_deposit_limit = MAX_SAFE_UINT256; token_network_deposit_limit = MAX_SAFE_UINT256; } /// @notice For backwards compatibility and testing only /// This can probably be removed once https://github.com/ethereum/web3.py/issues/1677 is fixed. function chain_id() external returns (uint256) { return block.chainid; } }
@dev Get the hash of the participant addresses, ordered lexicographically @param participant Address of a channel participant @param partner Address of the other channel participant
function getParticipantsHash(address participant, address partner) public pure returns (bytes32) { require(participant != address(0x0), "TN: participant address zero"); require(partner != address(0x0), "TN: partner address zero"); require(participant != partner, "TN: identical addresses"); if (participant < partner) { return keccak256(abi.encodePacked(participant, partner)); return keccak256(abi.encodePacked(partner, participant)); } }
2,193,586
[ 1, 967, 326, 1651, 434, 326, 14188, 6138, 16, 5901, 30089, 8829, 6478, 225, 14188, 5267, 434, 279, 1904, 14188, 225, 19170, 5267, 434, 326, 1308, 1904, 14188, 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, 13657, 27620, 2310, 12, 2867, 14188, 16, 1758, 19170, 13, 203, 3639, 1071, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 2583, 12, 2680, 14265, 480, 1758, 12, 20, 92, 20, 3631, 315, 56, 50, 30, 14188, 1758, 3634, 8863, 203, 3639, 2583, 12, 31993, 480, 1758, 12, 20, 92, 20, 3631, 315, 56, 50, 30, 19170, 1758, 3634, 8863, 203, 3639, 2583, 12, 2680, 14265, 480, 19170, 16, 315, 56, 50, 30, 12529, 6138, 8863, 203, 203, 3639, 309, 261, 2680, 14265, 411, 19170, 13, 288, 203, 5411, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2680, 14265, 16, 19170, 10019, 203, 5411, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 31993, 16, 14188, 10019, 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 ]
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds" ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/interfaces/IERC165.sol pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/Authorizable.sol pragma solidity >=0.4.22 <0.9.0; contract Authorizable is Ownable { address public trustee; constructor() { trustee = address(0x0); } modifier onlyAuthorized() { require(msg.sender == trustee || msg.sender == owner()); _; } function setTrustee(address _newTrustee) public onlyOwner { trustee = _newTrustee; } } // File: contracts/FeralfileArtworkV2.sol pragma solidity ^0.8.0; contract FeralfileExhibitionV2 is ERC721Enumerable, Authorizable, IERC2981 { using Strings for uint256; // royalty payout address address public royaltyPayoutAddress; // The maximum limit of edition size for each exhibitions uint256 public immutable maxEditionPerArtwork; // the basis points of royalty payments for each secondary sales uint256 public immutable secondarySaleRoyaltyBPS; // the maximum basis points of royalty payments uint256 public constant MAX_ROYALITY_BPS = 100_00; // token base URI string private _tokenBaseURI; // contract URI string private _contractURI; /// @notice A structure for Feral File artwork struct Artwork { string title; string artistName; string fingerprint; uint256 editionSize; } struct ArtworkEdition { uint256 editionID; string ipfsCID; } uint256[] private _allArtworks; mapping(uint256 => Artwork) public artworks; // artworkID => Artwork mapping(uint256 => ArtworkEdition) public artworkEditions; // artworkEditionID => ArtworkEdition mapping(uint256 => uint256[]) internal allArtworkEditions; // artworkID => []ArtworkEditionID mapping(uint256 => bool) internal registeredBitmarks; // bitmarkID => bool mapping(string => bool) internal registeredIPFSCIDs; // ipfsCID => bool constructor( string memory name_, string memory symbol_, uint256 maxEditionPerArtwork_, uint256 secondarySaleRoyaltyBPS_, address royaltyPayoutAddress_, string memory contractURI_, string memory tokenBaseURI_ ) ERC721(name_, symbol_) { require( maxEditionPerArtwork_ > 0, "maxEdition of each artwork in an exhibition needs to be greater than zero" ); require( secondarySaleRoyaltyBPS_ <= MAX_ROYALITY_BPS, "royalty BPS for secondary sales can not be greater than the maximum royalty BPS" ); require( royaltyPayoutAddress_ != address(0), "invalid royalty payout address" ); maxEditionPerArtwork = maxEditionPerArtwork_; secondarySaleRoyaltyBPS = secondarySaleRoyaltyBPS_; royaltyPayoutAddress = royaltyPayoutAddress_; _contractURI = contractURI_; _tokenBaseURI = tokenBaseURI_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @notice Call to create an artwork in the exhibition /// @param fingerprint - the fingerprint of an artwork /// @param title - the title of an artwork /// @param artistName - the artist of an artwork /// @param editionSize - the maximum edition size of an artwork function createArtwork( string memory fingerprint, string memory title, string memory artistName, uint256 editionSize ) external onlyAuthorized { require(bytes(title).length != 0, "title can not be empty"); require(bytes(artistName).length != 0, "artist can not be empty"); require(bytes(fingerprint).length != 0, "fingerprint can not be empty"); require(editionSize > 0, "edition size needs to be at least 1"); require( editionSize <= maxEditionPerArtwork, "artwork edition size exceeds the maximum edition size of the exhibition" ); uint256 artworkID = uint256(keccak256(abi.encode(fingerprint))); /// @notice make sure the artwork have not been registered require( bytes(artworks[artworkID].fingerprint).length == 0, "an artwork with the same fingerprint has already registered" ); Artwork memory artwork = Artwork( fingerprint, title, artistName, editionSize ); _allArtworks.push(artworkID); artworks[artworkID] = artwork; emit NewArtwork(artworkID); } /// @notice Return a count of artworks registered in this exhibition function totalArtworks() public view virtual returns (uint256) { return _allArtworks.length; } /// @notice Return the token identifier for the `index`th artwork function getArtworkByIndex(uint256 index) public view virtual returns (uint256) { require( index < totalArtworks(), "artworks: global index out of bounds" ); return _allArtworks[index]; } /// @notice Swap an existent artwork from bitmark to ERC721 /// @param artworkID - the artwork id where the new edition is referenced to /// @param bitmarkID - the bitmark id of artwork edition before swapped /// @param editionNumber - the edition number of the artwork edition /// @param owner - the owner address of the new minted token /// @param ipfsCID - the IPFS cid for the new token function swapArtworkFromBitmark( uint256 artworkID, uint256 bitmarkID, uint256 editionNumber, address owner, string memory ipfsCID ) external onlyAuthorized { /// @notice the edition size is not set implies the artwork is not created require(artworks[artworkID].editionSize > 0, "artwork is not found"); /// @notice The range of editionNumber should be between 0 (AP) ~ artwork.editionSize require( editionNumber <= artworks[artworkID].editionSize, "edition number exceed the edition size of the artwork" ); require(owner != address(0), "invalid owner address"); require(!registeredBitmarks[bitmarkID], "bitmark id has registered"); require(!registeredIPFSCIDs[ipfsCID], "ipfs id has registered"); uint256 editionID = artworkID + editionNumber; require( artworkEditions[editionID].editionID == 0, "the edition is existent" ); ArtworkEdition memory edition = ArtworkEdition(editionID, ipfsCID); artworkEditions[editionID] = edition; allArtworkEditions[artworkID].push(editionID); registeredBitmarks[bitmarkID] = true; registeredIPFSCIDs[ipfsCID] = true; _safeMint(owner, editionID); emit NewArtworkEdition(owner, artworkID, editionID); } /// @notice Update the IPFS cid of an edition to a new value function updateArtworkEditionIPFSCid(uint256 tokenId, string memory ipfsCID) external onlyAuthorized { require(_exists(tokenId), "artwork edition is not found"); require(!registeredIPFSCIDs[ipfsCID], "ipfs id has registered"); ArtworkEdition storage edition = artworkEditions[tokenId]; delete registeredIPFSCIDs[edition.ipfsCID]; registeredIPFSCIDs[ipfsCID] = true; edition.ipfsCID = ipfsCID; } /// @notice setRoyaltyPayoutAddress assigns a payout address so // that we can split the royalty. /// @param royaltyPayoutAddress_ - the new royalty payout address function setRoyaltyPayoutAddress(address royaltyPayoutAddress_) external onlyAuthorized { require( royaltyPayoutAddress_ != address(0), "invalid royalty payout address" ); royaltyPayoutAddress = royaltyPayoutAddress_; } /// @notice Return the edition counts for an artwork function totalEditionOfArtwork(uint256 artworkID) public view returns (uint256) { return allArtworkEditions[artworkID].length; } /// @notice Return the edition id of an artwork by index function getArtworkEditionByIndex(uint256 artworkID, uint256 index) public view returns (uint256) { require(index < totalEditionOfArtwork(artworkID)); return allArtworkEditions[artworkID][index]; } /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _tokenBaseURI; if (bytes(baseURI).length == 0) { baseURI = "ipfs://"; } return string( abi.encodePacked( baseURI, artworkEditions[tokenId].ipfsCID, "/metadata.json" ) ); } /// @notice Update the base URI for all tokens function setTokenBaseURI(string memory baseURI_) external onlyAuthorized { _tokenBaseURI = baseURI_; } /// @notice A URL for the opensea storefront-level metadata function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param tokenId - the NFT asset queried for royalty information /// @param salePrice - the sale price of the NFT asset specified by tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for salePrice function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require( _exists(tokenId), "ERC2981: query royalty info for nonexistent token" ); receiver = royaltyPayoutAddress; royaltyAmount = (salePrice * secondarySaleRoyaltyBPS) / MAX_ROYALITY_BPS; } event NewArtwork(uint256 indexed artworkID); event NewArtworkEdition( address indexed owner, uint256 indexed artworkID, uint256 indexed editionID ); }
@notice Return a count of artworks registered in this exhibition
function totalArtworks() public view virtual returns (uint256) { return _allArtworks.length; }
38,766
[ 1, 990, 279, 1056, 434, 3688, 18597, 4104, 316, 333, 431, 15769, 608, 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, 565, 445, 2078, 4411, 18597, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 454, 4411, 18597, 18, 2469, 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 ]
./full_match/80001/0xFAAed55Cac3D691257d5250E29aDcfeF720744e3/sources/project_/contracts/HSBCFCNContext6MUSD.sol
* @dev Returns aggregate nominal amount 10 decimals./
function NominalPrincipalAmount() public pure returns (uint256) { return 5000000000; }
5,557,039
[ 1, 1356, 7047, 12457, 1490, 3844, 225, 1728, 225, 15105, 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 ]
[ 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, 423, 362, 1490, 9155, 6275, 1435, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1381, 2787, 11706, 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.4.15; import "../Oracles/Oracle.sol"; import "../Tokens/Token.sol"; import "../Utils/Math.sol"; /// @title Ultimate oracle contract - Allows to swap oracle result for ultimate oracle result /// @author Stefan George - <[email protected]> contract UltimateOracle is Oracle { using Math for *; /* * Events */ event ForwardedOracleOutcomeAssignment(int outcome); event OutcomeChallenge(address indexed sender, int outcome); event OutcomeVote(address indexed sender, int outcome, uint amount); event Withdrawal(address indexed sender, uint amount); /* * Storage */ Oracle public forwardedOracle; Token public collateralToken; uint8 public spreadMultiplier; uint public challengePeriod; uint public challengeAmount; uint public frontRunnerPeriod; int public forwardedOutcome; uint public forwardedOutcomeSetTimestamp; int public frontRunner; uint public frontRunnerSetTimestamp; uint public totalAmount; mapping (int => uint) public totalOutcomeAmounts; mapping (address => mapping (int => uint)) public outcomeAmounts; /* * Public functions */ /// @dev Constructor sets ultimate oracle properties /// @param _forwardedOracle Oracle address /// @param _collateralToken Collateral token address /// @param _spreadMultiplier Defines the spread as a multiple of the money bet on other outcomes /// @param _challengePeriod Time to challenge oracle outcome /// @param _challengeAmount Amount to challenge the outcome /// @param _frontRunnerPeriod Time to overbid the front-runner function UltimateOracle( Oracle _forwardedOracle, Token _collateralToken, uint8 _spreadMultiplier, uint _challengePeriod, uint _challengeAmount, uint _frontRunnerPeriod ) public { // Validate inputs require( address(_forwardedOracle) != 0 && address(_collateralToken) != 0 && _spreadMultiplier >= 2 && _challengePeriod > 0 && _challengeAmount > 0 && _frontRunnerPeriod > 0); forwardedOracle = _forwardedOracle; collateralToken = _collateralToken; spreadMultiplier = _spreadMultiplier; challengePeriod = _challengePeriod; challengeAmount = _challengeAmount; frontRunnerPeriod = _frontRunnerPeriod; } /// @dev Allows to set oracle outcome function setForwardedOutcome() public { // There was no challenge and the outcome was not set yet in the ultimate oracle but in the forwarded oracle require( !isChallenged() && forwardedOutcomeSetTimestamp == 0 && forwardedOracle.isOutcomeSet()); forwardedOutcome = forwardedOracle.getOutcome(); forwardedOutcomeSetTimestamp = now; ForwardedOracleOutcomeAssignment(forwardedOutcome); } /// @dev Allows to challenge the oracle outcome /// @param _outcome Outcome to bid on function challengeOutcome(int _outcome) public { // There was no challenge yet or the challenge period expired require( !isChallenged() && !isChallengePeriodOver() && collateralToken.transferFrom(msg.sender, this, challengeAmount)); outcomeAmounts[msg.sender][_outcome] = challengeAmount; totalOutcomeAmounts[_outcome] = challengeAmount; totalAmount = challengeAmount; frontRunner = _outcome; frontRunnerSetTimestamp = now; OutcomeChallenge(msg.sender, _outcome); } /// @dev Allows to challenge the oracle outcome /// @param _outcome Outcome to bid on /// @param amount Amount to bid function voteForOutcome(int _outcome, uint amount) public { uint maxAmount = (totalAmount - totalOutcomeAmounts[_outcome]).mul(spreadMultiplier); if (maxAmount > totalOutcomeAmounts[_outcome]) maxAmount -= totalOutcomeAmounts[_outcome]; else maxAmount = 0; if (amount > maxAmount) amount = maxAmount; // Outcome is challenged and front runner period is not over yet and tokens can be transferred require( isChallenged() && !isFrontRunnerPeriodOver() && collateralToken.transferFrom(msg.sender, this, amount)); outcomeAmounts[msg.sender][_outcome] = outcomeAmounts[msg.sender][_outcome].add(amount); totalOutcomeAmounts[_outcome] = totalOutcomeAmounts[_outcome].add(amount); totalAmount = totalAmount.add(amount); if (_outcome != frontRunner && totalOutcomeAmounts[_outcome] > totalOutcomeAmounts[frontRunner]) { frontRunner = _outcome; frontRunnerSetTimestamp = now; } OutcomeVote(msg.sender, _outcome, amount); } /// @dev Withdraws winnings for user /// @return Winnings function withdraw() public returns (uint amount) { // Outcome was challenged and ultimate outcome decided require(isFrontRunnerPeriodOver()); amount = totalAmount.mul(outcomeAmounts[msg.sender][frontRunner]) / totalOutcomeAmounts[frontRunner]; outcomeAmounts[msg.sender][frontRunner] = 0; // Transfer earnings to contributor require(collateralToken.transfer(msg.sender, amount)); Withdrawal(msg.sender, amount); } /// @dev Checks if time to challenge the outcome is over /// @return Is challenge period over? function isChallengePeriodOver() public returns (bool) { return forwardedOutcomeSetTimestamp != 0 && now.sub(forwardedOutcomeSetTimestamp) > challengePeriod; } /// @dev Checks if time to overbid the front runner is over /// @return Is front runner period over? function isFrontRunnerPeriodOver() public returns (bool) { return frontRunnerSetTimestamp != 0 && now.sub(frontRunnerSetTimestamp) > frontRunnerPeriod; } /// @dev Checks if outcome was challenged /// @return Is challenged? function isChallenged() public returns (bool) { return frontRunnerSetTimestamp != 0; } /// @dev Returns if winning outcome is set /// @return Is outcome set? function isOutcomeSet() public constant returns (bool) { return isChallengePeriodOver() && !isChallenged() || isFrontRunnerPeriodOver(); } /// @dev Returns winning outcome /// @return Outcome function getOutcome() public constant returns (int) { if (isFrontRunnerPeriodOver()) return frontRunner; return forwardedOutcome; } }
@dev Withdraws winnings for user @return Winnings Outcome was challenged and ultimate outcome decided Transfer earnings to contributor
function withdraw() public returns (uint amount) { require(isFrontRunnerPeriodOver()); amount = totalAmount.mul(outcomeAmounts[msg.sender][frontRunner]) / totalOutcomeAmounts[frontRunner]; outcomeAmounts[msg.sender][frontRunner] = 0; require(collateralToken.transfer(msg.sender, amount)); Withdrawal(msg.sender, amount); }
12,620,245
[ 1, 1190, 9446, 87, 5657, 82, 899, 364, 729, 327, 21628, 82, 899, 2976, 5624, 1703, 462, 7862, 2423, 471, 225, 406, 4988, 12884, 2109, 13898, 12279, 425, 1303, 899, 358, 31123, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 1435, 203, 3639, 1071, 203, 3639, 1135, 261, 11890, 3844, 13, 203, 565, 288, 203, 3639, 2583, 12, 291, 9580, 9709, 5027, 4851, 10663, 203, 3639, 3844, 273, 2078, 6275, 18, 16411, 12, 21672, 6275, 87, 63, 3576, 18, 15330, 6362, 10211, 9709, 5717, 342, 2078, 19758, 6275, 87, 63, 10211, 9709, 15533, 203, 3639, 12884, 6275, 87, 63, 3576, 18, 15330, 6362, 10211, 9709, 65, 273, 374, 31, 203, 3639, 2583, 12, 12910, 2045, 287, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 3844, 10019, 203, 3639, 3423, 9446, 287, 12, 3576, 18, 15330, 16, 3844, 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 ]
./full_match/137/0xF0C117E2211123fdd19e1dE79229177FEC63B033/sources/contracts/Nintable.sol
Mints a new BLCKSPHR NFT
function mint(address player, string memory tokenURI, string memory characteristic, string memory color) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); uint256 currentGen = _gen.current(); _mint(player, newItemId); _setTokenURI(newItemId, tokenURI); _setArtProperty(newItemId, ArtProperty(currentGen, characteristic, color)); return newItemId; }
4,722,899
[ 1, 49, 28142, 279, 394, 19238, 3507, 3118, 15024, 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, 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, 312, 474, 12, 2867, 7291, 16, 533, 3778, 1147, 3098, 16, 533, 3778, 23158, 16, 533, 3778, 2036, 13, 203, 3639, 1071, 1338, 5541, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 3639, 2254, 5034, 783, 7642, 273, 389, 4507, 18, 2972, 5621, 203, 3639, 389, 81, 474, 12, 14872, 16, 394, 17673, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 2704, 17673, 16, 1147, 3098, 1769, 203, 3639, 389, 542, 4411, 1396, 12, 2704, 17673, 16, 9042, 1396, 12, 2972, 7642, 16, 23158, 16, 2036, 10019, 203, 203, 3639, 327, 394, 17673, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-10-17 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.6; // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/EnumerableMap /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @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); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: OpenZeppelin/[email protected]/Strings /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: EtherMonad.sol contract Monad is Ownable, ERC721 { struct MonadMetadata { uint256 rdmPercent; uint32 attack; uint32 protection; uint32 ability; uint32 environment; } mapping(uint256 => MonadMetadata) idToMonad; enum Stage { Emission, Redeem, Arsenal } //0,00002 ether uint256 public constant monadPriceIncrease = 2 * 1e13; uint32 public constant maxMonadPurchase = 10; uint256 private mintDelta = 66 * monadPriceIncrease; Stage stage; string private _currentBaseURI; uint256 public redeemStageStart; uint256 public lastMintTime; uint256 public mintIntervalTime; uint256 public monadPrice; uint256 public redeemPercentCntr; uint256 public fullBank; constructor() ERC721("Monad Arsenal", "MONAD") { setBaseURI("https://monadcf.club/metadata/"); fullBank = 0; stage = Stage.Emission; redeemStageStart = 0; lastMintTime = block.timestamp; mintIntervalTime = 30 days; //0.015 ether(1 ether = 1e18) monadPrice = 15 * 1e15; redeemPercentCntr = 1e13 * 8 / 1000; } function getMonadStage() public view virtual returns (string memory) { if (stage == Stage.Emission) return "Emission"; else if (stage == Stage.Redeem) return "Redeem"; else return "Arsenal"; } function mintNMonads(uint256 numberOfMonads) external payable { require(numberOfMonads <= maxMonadPurchase, "Can only mint 10 monads at a time"); uint256 FullMPrice = (2 * monadPrice + monadPriceIncrease * (numberOfMonads - 1 )) / 2 * numberOfMonads; require(FullMPrice <= msg.value, "Ether value sent is not correct"); if ((block.timestamp - lastMintTime) > mintIntervalTime) { stage = Stage.Redeem; } require(stage == Stage.Emission, "Too late to mint Monad"); for(uint i = 0; i < numberOfMonads; i++) { generateMonadMetadata(totalSupply()); lastMintTime = block.timestamp; monadPrice = monadPrice + monadPriceIncrease; if (mintIntervalTime > 3600) mintIntervalTime = mintIntervalTime * 998 / 1000; redeemPercentCntr = redeemPercentCntr * 992 / 1000; _safeMint(msg.sender, totalSupply()); } } function getNMonadsPrice(uint32 numberOfMonads) public view virtual returns (uint256) { require( (0 < numberOfMonads) && (numberOfMonads <= maxMonadPurchase), "You can only create 1 to 10 monads at a time"); uint256 FullMPrice = (2 * monadPrice + monadPriceIncrease * (numberOfMonads - 1 )) / 2 * numberOfMonads + mintDelta; return FullMPrice; } function startRedeemStage() external payable { if ((block.timestamp - lastMintTime) > mintIntervalTime) { stage = Stage.Redeem; } require(stage == Stage.Redeem, "Too soon to start redemption stage"); redeemStageStart = block.timestamp; fullBank = address(this).balance; payable(owner()).transfer(address(this).balance * 2 / 10); MonadMetadata memory monad = idToMonad[totalSupply() - 1]; monad.rdmPercent = 1e13; idToMonad[totalSupply() - 1] = monad; } function redeemMonad(uint256 tokenId) external payable { require(stage == Stage.Redeem, "Too soon to start redemption stage"); require(_exists(tokenId), "Monad doesn't exist"); require(ownerOf(tokenId) == msg.sender, "Only owner can redeem monad"); MonadMetadata memory monad = idToMonad[tokenId]; uint256 redeemMPrice = fullBank * 4 / 10 * monad.rdmPercent / 1e13; safeTransferFrom(msg.sender, owner(), tokenId); payable(msg.sender).transfer(redeemMPrice); } function startArsenalStage() external payable { require(stage == Stage.Redeem, "Arsenal only after Redeem"); if ((block.timestamp - redeemStageStart) > 30 days) { stage = Stage.Arsenal; } require(stage == Stage.Arsenal, "Too soon to start arsenal stage"); payable(owner()).transfer(address(this).balance); } function setBaseURI(string memory _baseURI) public onlyOwner { _currentBaseURI = _baseURI; } function baseURI() public view virtual override returns (string memory) { return _currentBaseURI; } function getMonadRdmRate(uint256 tokenId) public view virtual returns (uint256) { MonadMetadata memory monad = idToMonad[tokenId]; return monad.rdmPercent; } function getMonadTraits(uint256 tokenId) public view returns (uint32, uint32, uint32, uint32) { MonadMetadata memory monad = idToMonad[tokenId]; return (monad.attack, monad.protection, monad.ability, monad.environment); } function generateMonadMetadata(uint256 tokenId) internal { uint256 random = pseudoRNG(tokenId); uint32 monadAttack = getValueFromRandom(random); uint32 monadProtection = getValueFromRandom(random / 2 ** 64); uint32 monadAbility = getValueFromRandom(random / 2 ** 128); uint32 monadEnvironment = getValueFromRandom(random / 2 ** 192); idToMonad[tokenId] = MonadMetadata(redeemPercentCntr, monadAttack, monadProtection, monadAbility, monadEnvironment); } function getValueFromRandom(uint256 randVal) internal pure returns (uint32) { uint32 trait; uint256 r = randVal % 1000000; if (r < 40000) { trait = 0; } else if (r < 100000) { trait = 1; } else if (r < 160000) { trait = 2; } else if (r < 220000) { trait = 3; } else if (r < 480000) { trait = 4; } else if (r < 740000) { trait = 5; } else { trait = 6; } return trait; } function pseudoRNG(uint256 tokenId) internal view returns (uint256) { return uint256(keccak256(abi.encode(block.timestamp, msg.sender, block.difficulty, tokenId))); } }
0.015 ether(1 ether = 1e18)
constructor() ERC721("Monad Arsenal", "MONAD") { fullBank = 0; stage = Stage.Emission; redeemStageStart = 0; lastMintTime = block.timestamp; mintIntervalTime = 30 days; monadPrice = 15 * 1e15; redeemPercentCntr = 1e13 * 8 / 1000; }
7,966,507
[ 1, 20, 18, 1611, 25, 225, 2437, 12, 21, 225, 2437, 273, 404, 73, 2643, 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, 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, 3885, 1435, 4232, 39, 27, 5340, 2932, 11415, 361, 1201, 87, 275, 287, 3113, 315, 17667, 1880, 7923, 288, 203, 3639, 1983, 16040, 273, 374, 31, 203, 3639, 6009, 273, 16531, 18, 1514, 19710, 31, 203, 3639, 283, 24903, 8755, 1685, 273, 374, 31, 203, 3639, 1142, 49, 474, 950, 273, 1203, 18, 5508, 31, 203, 3639, 312, 474, 4006, 950, 273, 5196, 4681, 31, 203, 3639, 6921, 361, 5147, 273, 4711, 380, 404, 73, 3600, 31, 203, 203, 3639, 283, 24903, 8410, 21111, 313, 273, 404, 73, 3437, 380, 1725, 342, 4336, 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 ]
./partial_match/97/0xcD56a1fC2811f0a553b06cA43A679e3d4018D97A/sources/StrategyHelperV1.sol
= 0x1B96B92314C44b159149f7E0303511fB2Fc4774f;
address public BNB_BUSD_POOL;
11,355,166
[ 1, 33, 374, 92, 21, 38, 10525, 38, 29, 4366, 3461, 39, 6334, 70, 24872, 26262, 74, 27, 41, 4630, 4630, 25, 2499, 74, 38, 22, 42, 71, 24, 4700, 24, 74, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1758, 1071, 225, 605, 20626, 67, 3000, 9903, 67, 20339, 31, 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, -100 ]
./partial_match/3/0x46485db806C892D8673138eA6e1c7a21E6B395C7/sources/Dice.sol
Check Game Players Balance Emit events of this game
function tempDiceGame( address[] memory playerList, uint256[] memory playerScoreList, uint256 playAmount, uint256 gameLength ) public payable onlyOwner returns (bool) { for (uint256 i = 0; i < gameLength; i++) { require( _playerETHBalance[playerList[i]] >= playAmount, "The balance of all players should be more than playAmount." ); } for (uint256 i = 1; i < gameLength; i++) { if (playerScoreList[winnerId] < playerScoreList[i]) { winnerId = i; } } uint256 winnerAmount = totalGameAmount.mul(_winnerPercent).div(10000); uint256 feeAmount = totalGameAmount.sub(winnerAmount); _totalFeeAmount = _totalFeeAmount.add(feeAmount); _totalETHAmount > winnerAmount, "Can't withdraw over total amount" ); (bool sent, bytes memory data) = require(sent, "Failed to withdraw Ether to Winner"); _totalETHAmount = _totalETHAmount.sub(winnerAmount); for (uint256 i = 0; i < gameLength; i++) { emit GamePlayerStatus( playerList[i], playAmount, playerScoreList[i] ); } emit GameWinner(playerList[winnerId], playerScoreList[winnerId]); emit WithdrawWinner(playerList[winnerId], winnerAmount); return true; }
5,340,931
[ 1, 1564, 14121, 3008, 3907, 30918, 16008, 2641, 434, 333, 7920, 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, 1906, 40, 1812, 12496, 12, 203, 3639, 1758, 8526, 3778, 7291, 682, 16, 203, 3639, 2254, 5034, 8526, 3778, 7291, 7295, 682, 16, 203, 3639, 2254, 5034, 6599, 6275, 16, 203, 3639, 2254, 5034, 7920, 1782, 203, 565, 262, 1071, 8843, 429, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 7920, 1782, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 389, 14872, 1584, 44, 13937, 63, 14872, 682, 63, 77, 13563, 1545, 6599, 6275, 16, 203, 7734, 315, 1986, 11013, 434, 777, 18115, 1410, 506, 225, 1898, 2353, 6599, 6275, 1199, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 404, 31, 277, 411, 7920, 1782, 31, 277, 27245, 288, 203, 5411, 309, 261, 14872, 7295, 682, 63, 91, 7872, 548, 65, 411, 7291, 7295, 682, 63, 77, 5717, 288, 203, 7734, 5657, 1224, 548, 273, 277, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 5657, 1224, 6275, 273, 2078, 12496, 6275, 18, 16411, 24899, 91, 7872, 8410, 2934, 2892, 12, 23899, 1769, 203, 3639, 2254, 5034, 14036, 6275, 273, 2078, 12496, 6275, 18, 1717, 12, 91, 7872, 6275, 1769, 203, 203, 3639, 389, 4963, 14667, 6275, 273, 389, 4963, 14667, 6275, 18, 1289, 12, 21386, 6275, 1769, 203, 203, 5411, 389, 4963, 1584, 44, 6275, 405, 5657, 1224, 6275, 16, 203, 5411, 315, 2568, 1404, 598, 9446, 1879, 2078, 3844, 6, 203, 3639, 11272, 203, 3639, 261, 6430, 2 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @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.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.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; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.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: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/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. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ 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()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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, _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 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 `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()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } 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.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: 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: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
* @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)); }
98,877
[ 1, 7244, 4369, 1245, 1375, 13290, 68, 635, 392, 16804, 12825, 2254, 5034, 16, 15226, 310, 603, 9391, 578, 16536, 635, 374, 18, 225, 1220, 903, 315, 74, 5807, 6, 326, 26708, 18, 225, 279, 279, 15038, 2148, 16730, 18, 225, 324, 279, 2254, 5034, 15030, 18, 327, 326, 26708, 434, 1375, 69, 68, 26057, 635, 1375, 70, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3739, 12, 13290, 3778, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 13290, 3778, 13, 288, 203, 3639, 327, 1351, 5679, 12, 69, 18, 1899, 620, 18, 2892, 12, 70, 10019, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC721/IERC721Full.sol"; import "openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title DDRMCore * @author rjkz808 * @dev The DDRM application core contract * * ██████╗ ██████╗ ██████╗ ███╗ ███╗ * ██╔══██╗██╔══██╗██╔══██╗████╗ ████║ * ██║ ██║██║ ██║██████╔╝██╔████╔██║ * ██║ ██║██║ ██║██╔══██╗██║╚██╔╝██║ * ██████╔╝██████╔╝██║ ██║██║ ╚═╝ ██║ * ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ * */ contract DDRMCore is IERC721Full, Ownable { using Address for address; using SafeMath for uint256; IERC20 private _token; bytes4 private _onERC721Received = 0x150b7a02; bytes4 private _interfaceIdERC165 = 0x01ffc9a7; bytes4 private _interfaceIdERC721 = 0x80ac58cd; bytes4 private _interfaceIdERC721Enumerable = 0x780e9d63; bytes4 private _interfaceIdERC721Metadata = 0x5b5e139f; string private _name = "DDRM"; string private _symbol = "DDRM"; uint256[] private _allTokens; struct Account { uint256[] ownedTokens; mapping (address => bool) operator; } struct Token { address owner; address approval; bytes4 asset; string uri; uint256 allTokensIndex; uint256 ownedTokensIndex; uint256 endTime; } mapping (address => Account) private _accounts; mapping (uint256 => Token) private _tokens; mapping (bytes4 => bool) private _interfaces; mapping (bytes4 => uint256) private _prices; /** * @dev Reverts if the `msg.sender` cannot spend the specified token * @param tokenId uint256 ID of the token to query the spender of */ modifier canSpend(uint256 tokenId) { require( // solium-disable-next-line operator-whitespace msg.sender == ownerOf(tokenId) || msg.sender == getApproved(tokenId) || isApprovedForAll(ownerOf(tokenId), msg.sender), "the msg.sender isn't owner, approval or operator of the specified token" ); _; } /** * @dev Constructor sets the ERC20 token instance and registers the ERC165 * implemented interfaces * @param token IERC20 the ERC20 token contract */ constructor(IERC20 token) public { require(address(token) != address(0), "zero address specified as a token contract"); _token = token; _registerInterface(_interfaceIdERC165); _registerInterface(_interfaceIdERC721); _registerInterface(_interfaceIdERC721Enumerable); _registerInterface(_interfaceIdERC721Metadata); } /** * @dev Gets the token name * @return string the token name */ function name() external view returns (string) { return _name; } /** * @dev Gets the token short code * @return string the token symbol */ function symbol() external view returns (string) { return _symbol; } /** * @dev Gets the specified token URI * @param tokenId uint256 ID of the token to query the URI of * @return string the token URI */ function tokenURI(uint256 tokenId) external view returns (string) { require(_exists(tokenId), "the specified token doesn't exist"); return _tokens[tokenId].uri; } /** * @dev Gets the contract interface implementation state * @param interfaceId bytes4 ERC615 ID of the interface to query the * implementation state of * @return bool `true` if implements, `false` otherwise */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _interfaces[interfaceId]; } /** * @dev Gets the total issued tokens amount * @return uint256 the total tokens supply */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the contract ERC20 token instance * @return IERC20 tht ERC20 token instance */ function token() public view returns (IERC20) { return _token; } /** * @dev Gets an account tokens balance * @param owner address an account to query the balance of * @return uint256 the account owned tokens amount */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "zero address specified as a tokens owner"); return _accounts[owner].ownedTokens.length; } /** * @dev Gets the specified token owner address * @param tokenId uint256 ID of the token to query the owner of * @return address the token owner */ function ownerOf(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "the specified token doesn't exist"); return _tokens[tokenId].owner; } /** * @dev Gets the specified token approved address * @param tokenId uint256 ID of the token to query the approval of * @return address the token approval */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "the specified token doesn't exist"); return _tokens[tokenId].approval; } /** * @dev Gets the specified token end time * @param tokenId uint256 ID of the token to query the end time of * @return uint256 the token end time */ function endTimeOf(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "the specified token doesn't exist"); return _tokens[tokenId].endTime; } /** * @dev Gets the specified token asset * @param tokenId uint256 ID of the token to query the asset of * @return bytes4 ID of the asset to wich the token is attached */ function assetOf(uint256 tokenId) public view returns (bytes4) { require(_exists(tokenId), "the specified token doesn't exist"); return _tokens[tokenId].asset; } /** * @dev Gets the token ID that is at the specified index in the allTokens * array * @param index uint256 the ownedTokens array index * @return uint256 ID of the token that is at the specified index in the * allTokens array */ function tokenByIndex(uint256 index) public view returns (uint256) { require( index < totalSupply(), "the token index should be less than the total tokens supply"); return _allTokens[index]; } /** * @dev Gets the specified asset price * @param assetId bytes4 ID of the asset to query the price of * @return uint256 the asset price */ function assetPrice(bytes4 assetId) public view returns (uint256) { return _prices[assetId]; } /** * @dev Get the specified accounts operator approval state * @param owner address the tokens owner * @param operator address the tokens operator * @return bool `true` if exists, `false` otherwise */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _accounts[owner].operator[operator]; } /** * @dev Gets the token ID that is at the specified index in the specified * account ownedTokens array * @param owner address the token owner * @param index uint256 index of the token in the ownedTokens array * @return uint256 ID of the token that is at the specified index in the * ownedTokens array */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(owner != address(0), "zero address specified as a token owner"); require( index < balanceOf(owner), "the token index should be less than the specified token owner balance"); return _accounts[owner].ownedTokens[index]; } /** * @dev Approves an account to spend the specified token * @param spender address the tokens spender * @param tokenId uint256 ID of the token to be approved */ function approve(address spender, uint256 tokenId) public { require( spender != ownerOf(tokenId), "the specified address cannot be the token approval"); require( msg.sender == ownerOf(tokenId) || isApprovedForAll(ownerOf(tokenId), msg.sender), "the msg.sender isn't owner or operator of the specified token" ); _tokens[tokenId].approval = spender; emit Approval(ownerOf(tokenId), spender, tokenId); } /** * @dev Allowed the specified operator to spend the owned tokens * @param operator address the tokens operator * @param approved bool the operator approval state */ function setApprovalForAll(address operator, bool approved) public { require(operator != address(0), "zero address specified as an operator"); _accounts[msg.sender].operator[operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Transfers the specified spending tokens amount to an account * @param from address the tokens owner * @param to address the tokens recipient * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public canSpend(tokenId) { _clearApproval(tokenId); _removeTokenFrom(from, tokenId); _addTokenTo(to, tokenId); emit Transfer(from, to, tokenId); } /** * @dev Transfers the specified spending tokens amount to an account. If the * tokens recipient is a contract calls the onERC721Received function * @param from address the tokens owner * @param to address the tokens recipient * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Transfers the specified spending tokens amount to an account. If the * tokens recipient is a contract calls the onERC721Received function * @param from address the tokens owner * @param to address the tokens recipient * @param tokenId uint256 ID of the token to be transferred * @param data bytes the transaction metadata */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public { transferFrom(from, to, tokenId); _callRecipient(from, to, tokenId, data); } /** * @dev Burns the specified token * @param tokenId uint256 ID of the token to be burned */ function burn(uint256 tokenId) public canSpend(tokenId) { address owner = ownerOf(tokenId); _removeTokenFrom(owner, tokenId); delete _tokens[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Function to buy the specified asset token * @param recipient address the token recipient * @param assetId bytes4 ID of the asset to buy the token of */ function buyToken(address recipient, bytes4 assetId) public { require(recipient != address(0), "zero address specified as a token recipient"); require( _token.allowance(msg.sender, address(this)) >= assetPrice(assetId), "the msg.sender allowance is less than the specified asset price"); _token.transferFrom(msg.sender, address(this), assetPrice(assetId)); _mint(recipient, assetId, totalSupply().add(1), block.timestamp.add(30 days)); } /** * @dev Transfers tokens earned for the assets sale to the contract owner */ function withdraw() public onlyOwner { require( _token.balanceOf(address(this)) > 0, "the contract doesn't have any funds to send"); _token.transfer(owner(), _token.balanceOf(address(this))); } /** * @dev Transfers the specified expired token to the contract owner * @param tokenId uint256 ID of the token to be revoked */ function revokeToken(uint256 tokenId) public onlyOwner { require(endTimeOf(tokenId) < block.timestamp, "the specified token is still valid"); address tokenOwner = ownerOf(tokenId); _clearApproval(tokenId); _removeTokenFrom(tokenOwner, tokenId); _addTokenTo(owner(), tokenId); emit Transfer(tokenOwner, owner(), tokenId); } /** * @dev Sets the specified asset price * @param assetId bytes4 ID of the asset to set the price of * @param price uint256 price of the specified asset */ function setAssetPrice(bytes4 assetId, uint256 price) public onlyOwner { require(assetId != 0xffffffff, "invalid asset ID specified"); _prices[assetId] = price; } /** * @dev Internal function that gets the specified token existence * @param tokenId uint256 ID of the token to query the existence of * @return bool `true` if the token exists, `false` otherwise */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokens[tokenId].owner != address(0); } /** * @dev Private function that clears an approval of the specified token * @param tokenId uint256 ID of the token to clear the approval of */ function _clearApproval(uint256 tokenId) private { require(_exists(tokenId), "the specified token doesn't exist"); Token storage approvedToken = _tokens[tokenId]; if (approvedToken.approval != address(0)) approvedToken.approval = address(0); } /** * @dev Private function that adds the specified token to an account * @param to address the token recipient * @param tokenId uint256 ID of the token to be added */ function _addTokenTo(address to, uint256 tokenId) private { require(to != address(0), "zero address specified as a token recipient"); require(!_exists(tokenId), "the specified token already exists"); Account storage recipient = _accounts[to]; Token storage tokenToAdd = _tokens[tokenId]; tokenToAdd.owner = to; tokenToAdd.ownedTokensIndex = recipient.ownedTokens.length; recipient.ownedTokens.push(tokenId); } /** * @dev Private function that removes the specified token from an account * @param from address the token owner * @param tokenId uint256 ID of the token to be removed */ function _removeTokenFrom(address from, uint256 tokenId) private { require( from == ownerOf(tokenId), "the specified address isn't the specified token owner"); Account storage owner = _accounts[from]; Token storage tokenToRemove = _tokens[tokenId]; uint256 lastTokenId = owner.ownedTokens[balanceOf(from).sub(1)]; Token storage lastToken = _tokens[lastTokenId]; owner.ownedTokens[tokenToRemove.ownedTokensIndex] = lastTokenId; owner.ownedTokens.length = owner.ownedTokens.length.sub(1); lastToken.ownedTokensIndex = tokenToRemove.ownedTokensIndex; tokenToRemove.ownedTokensIndex = 0; tokenToRemove.owner = address(0); } /** * @dev Private function that calls the contract recipient * `onERC721Received` function and checks that the return value is equal to * the _onERC721Received value * @param from address the token owner * @param to address the token recipient * @param tokenId uint256 ID of the tokens to be transferred * @param data bytes the transaction metadata */ function _callRecipient(address from, address to, uint256 tokenId, bytes data) private { if (to.isContract()) { require( _onERC721Received == IERC721Receiver(to).onERC721Received( msg.sender, from, tokenId, data ), "the specified address cannot receive tokens" ); } } /** * @dev Private function that emits the token and sends it to the specified * account * @param to address the token recipient * @param assetId bytes4 ID of the asset to wich the token is attached * @param tokenId uint256 ID of the token to be emitted * @param endTime uint256 the token end time */ function _mint(address to, bytes4 assetId, uint256 tokenId, uint256 endTime) private { _addTokenTo(to, tokenId); _tokens[tokenId].asset = assetId; _tokens[tokenId].endTime = endTime; _tokens[tokenId].allTokensIndex = _allTokens.length; _allTokens.push(tokenId); emit Transfer(address(0), to, tokenId); } /** * @dev Private function that sets the specified token URI * @param tokenId uint256 ID of the token to set the URI of * @param uri string the token URI */ function _setTokenURI(uint256 tokenId, string uri) private { require(_exists(tokenId), "the specified token doesn't exist"); Token storage ownedToken = _tokens[tokenId]; ownedToken.uri = uri; } /** * @dev Private function that registers the specified ERC165 interface * @param interfaceId bytes4 ID of the interface to register the * implementation of */ function _registerInterface(bytes4 interfaceId) private { require(interfaceId != 0xffffffff, "invalid interface ID specified"); _interfaces[interfaceId] = true; } }
* @dev Private function that clears an approval of the specified token @param tokenId uint256 ID of the token to clear the approval of/
function _clearApproval(uint256 tokenId) private { require(_exists(tokenId), "the specified token doesn't exist"); Token storage approvedToken = _tokens[tokenId]; if (approvedToken.approval != address(0)) approvedToken.approval = address(0); }
12,541,346
[ 1, 6014, 445, 716, 22655, 392, 23556, 434, 326, 1269, 1147, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 2424, 326, 23556, 434, 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 ]
[ 1, 1, 1, 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, 389, 8507, 23461, 12, 11890, 5034, 1147, 548, 13, 3238, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 5787, 1269, 1147, 3302, 1404, 1005, 8863, 203, 203, 3639, 3155, 2502, 20412, 1345, 273, 389, 7860, 63, 2316, 548, 15533, 203, 3639, 309, 261, 25990, 1345, 18, 12908, 1125, 480, 1758, 12, 20, 3719, 20412, 1345, 18, 12908, 1125, 273, 1758, 12, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x48F63Dcec1306bB2210B0D79bee7064050C18137/sources/RonazoStaking.sol
@dev Returns custody info of _addr
function getCustody(address _addr) public view returns (address _beneficiary, uint256 _heartbeat_interval, address _manager) { return (custody[_addr].beneficiary, custody[_addr].heartbeat_interval, custody[_addr].manager); }
4,261,895
[ 1, 1356, 276, 641, 973, 1123, 434, 389, 4793, 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, 225, 445, 1927, 641, 973, 12, 2867, 389, 4793, 13, 1071, 1476, 1135, 261, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 25445, 67, 6624, 16, 1758, 389, 4181, 13, 288, 203, 1377, 327, 261, 71, 641, 973, 63, 67, 4793, 8009, 70, 4009, 74, 14463, 814, 16, 276, 641, 973, 63, 67, 4793, 8009, 25445, 67, 6624, 16, 276, 641, 973, 63, 67, 4793, 8009, 4181, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: contracts/interfaces/IPriceModule.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; interface IPriceModule { function getUSDPrice(address ) external view returns(uint256); } // File: contracts/aps/APContract.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; // pragma experimental ABIEncoderV2; contract APContract { address public yieldsterDAO; address public yieldsterTreasury; address public yieldsterGOD; address public emergencyVault; address public yieldsterExchange; address public stringUtils; address public whitelistModule; address public whitelistManager; address public proxyFactory; address public priceModule; address public platFormManagementFee; address public profitManagementFee; address public stockDeposit; address public stockWithdraw; address public safeMinter; address public safeUtils; address public oneInch; struct Asset{ string name; string symbol; bool created; } struct Protocol{ string name; string symbol; bool created; } struct Vault { mapping(address => bool) vaultAssets; mapping(address => bool) vaultDepositAssets; mapping(address => bool) vaultWithdrawalAssets; mapping(address => bool) vaultEnabledStrategy; address depositStrategy; address withdrawStrategy; address vaultAPSManager; address vaultStrategyManager; uint256[] whitelistGroup; bool created; } struct VaultActiveStrategy { mapping(address => bool) isActiveStrategy; mapping(address => uint256) activeStrategyIndex; address[] activeStrategyList; } struct Strategy{ string strategyName; mapping(address => bool) strategyProtocols; bool created; address minter; address executor; address benefeciary; uint256 managementFeePercentage; } struct SmartStrategy{ string smartStrategyName; address minter; address executor; bool created; } struct vaultActiveManagemetFee { mapping(address => bool) isActiveManagementFee; mapping(address => uint256) activeManagementFeeIndex; address[] activeManagementFeeList; } event VaultCreation(address vaultAddress); mapping(address => vaultActiveManagemetFee) managementFeeStrategies; mapping(address => mapping(address => mapping(address => bool))) vaultStrategyEnabledProtocols; mapping(address => VaultActiveStrategy) vaultActiveStrategies; mapping(address => Asset) assets; mapping(address => Protocol) protocols; mapping(address => Vault) vaults; mapping(address => Strategy) strategies; mapping(address => SmartStrategy) smartStrategies; mapping(address => address) safeOwner; mapping(address => bool) APSManagers; mapping(address => address) minterStrategyMap; constructor( address _whitelistModule, address _platformManagementFee, address _profitManagementFee, address _stringUtils, address _yieldsterExchange, address _oneInch, address _priceModule, address _safeUtils ) public { yieldsterDAO = msg.sender; yieldsterTreasury = msg.sender; yieldsterGOD = msg.sender; emergencyVault = msg.sender; APSManagers[msg.sender] = true; whitelistModule = _whitelistModule; platFormManagementFee = _platformManagementFee; stringUtils = _stringUtils; yieldsterExchange = _yieldsterExchange; oneInch = _oneInch; priceModule = _priceModule; safeUtils = _safeUtils; profitManagementFee = _profitManagementFee; } /// @dev Function to add proxy Factory address to Yieldster. /// @param _proxyFactory Address of proxy factory. function addProxyFactory(address _proxyFactory) public onlyManager { proxyFactory = _proxyFactory; } function setProfitAndPlatformManagementFeeStrategies(address _platformManagement,address _profitManagement) public onlyYieldsterDAO { if (_profitManagement != address(0)) profitManagementFee = _profitManagement; if (_platformManagement != address(0)) platFormManagementFee = _platformManagement; } //Modifiers modifier onlyYieldsterDAO{ require(yieldsterDAO == msg.sender, "Only Yieldster DAO is allowed to perform this operation"); _; } modifier onlyManager{ require(APSManagers[msg.sender], "Only APS managers allowed to perform this operation!"); _; } modifier onlySafeOwner{ require(safeOwner[msg.sender] == tx.origin, "Only safe Owner can perform this operation"); _; } function isVault( address _address) public view returns(bool){ return vaults[_address].created; } /// @dev Function to add APS manager to Yieldster. /// @param _manager Address of the manager. function addManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = true; } /// @dev Function to remove APS manager from Yieldster. /// @param _manager Address of the manager. function removeManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = false; } /// @dev Function to change whitelist Manager. /// @param _whitelistManager Address of the whitelist manager. function changeWhitelistManager(address _whitelistManager) public onlyYieldsterDAO { whitelistManager = _whitelistManager; } /// @dev Function to set Yieldster GOD. /// @param _yieldsterGOD Address of the Yieldster GOD. function setYieldsterGOD(address _yieldsterGOD) public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = _yieldsterGOD; } /// @dev Function to disable Yieldster GOD. function disableYieldsterGOD() public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = address(0); } /// @dev Function to set Emergency vault. /// @param _emergencyVault Address of the Yieldster Emergency vault. function setEmergencyVault(address _emergencyVault) onlyYieldsterDAO public { emergencyVault = _emergencyVault; } /// @dev Function to set Safe Minter. /// @param _safeMinter Address of the Safe Minter. function setSafeMinter(address _safeMinter) onlyYieldsterDAO public { safeMinter = _safeMinter; } /// @dev Function to set safeUtils contract. /// @param _safeUtils Address of the safeUtils contract. function setSafeUtils(address _safeUtils) onlyYieldsterDAO public { safeUtils = _safeUtils; } /// @dev Function to set oneInch address. /// @param _oneInch Address of the oneInch. function setOneInch(address _oneInch) onlyYieldsterDAO public { oneInch = _oneInch; } /// @dev Function to get strategy address from minter. /// @param _minter Address of the minter. function getStrategyFromMinter(address _minter) external view returns(address) { return minterStrategyMap[_minter]; } /// @dev Function to set Yieldster Exchange. /// @param _yieldsterExchange Address of the Yieldster exchange. function setYieldsterExchange(address _yieldsterExchange) onlyYieldsterDAO public { yieldsterExchange = _yieldsterExchange; } /// @dev Function to set stock Deposit and Withdraw. /// @param _stockDeposit Address of the stock deposit contract. /// @param _stockWithdraw Address of the stock withdraw contract. function setStockDepositWithdraw(address _stockDeposit, address _stockWithdraw) onlyYieldsterDAO public { stockDeposit = _stockDeposit; stockWithdraw = _stockWithdraw; } /// @dev Function to change the APS Manager for a vault. /// @param _vaultAPSManager Address of the new APS Manager. function changeVaultAPSManager(address _vaultAPSManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultAPSManager = _vaultAPSManager; } /// @dev Function to change the Strategy Manager for a vault. /// @param _vaultStrategyManager Address of the new Strategy Manager. function changeVaultStrategyManager(address _vaultStrategyManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultStrategyManager = _vaultStrategyManager; } //Price Module /// @dev Function to set Yieldster price module. /// @param _priceModule Address of the price module. function setPriceModule(address _priceModule) public onlyManager { priceModule = _priceModule; } /// @dev Function to get the USD price for a token. /// @param _tokenAddress Address of the token. function getUSDPrice(address _tokenAddress) public view returns(uint256) { require(_isAssetPresent(_tokenAddress),"Asset not present!"); return IPriceModule(priceModule).getUSDPrice(_tokenAddress); } //Vaults /// @dev Function to create a vault. /// @param _owner Address of the owner of the vault. /// @param _vaultAddress Address of the new vault. function createVault(address _owner, address _vaultAddress) public { require(msg.sender == proxyFactory, "Only Proxy Factory can perform this operation"); safeOwner[_vaultAddress] = _owner; } /// @dev Function to add a vault in the APS. /// @param _vaultAPSManager Address of the vaults APS Manager. /// @param _vaultStrategyManager Address of the vaults Strateg Manager. /// @param _whitelistGroup List of whitelist groups applied to the vault. /// @param _owner Address of the vault owner. function addVault( address _vaultAPSManager, address _vaultStrategyManager, uint256[] memory _whitelistGroup, address _owner ) public { require(safeOwner[msg.sender] == _owner, "Only owner can call this function"); Vault memory newVault = Vault( { vaultAPSManager : _vaultAPSManager, vaultStrategyManager : _vaultStrategyManager, whitelistGroup : _whitelistGroup, depositStrategy: stockDeposit, withdrawStrategy: stockWithdraw, created : true }); vaults[msg.sender] = newVault; //applying Platform management fee managementFeeStrategies[msg.sender].isActiveManagementFee[platFormManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[platFormManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(platFormManagementFee); //applying Profit management fee managementFeeStrategies[msg.sender].isActiveManagementFee[profitManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[profitManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(profitManagementFee); } /// @dev Function to Manage the vault assets. /// @param _enabledDepositAsset List of deposit assets to be enabled in the vault. /// @param _enabledWithdrawalAsset List of withdrawal assets to be enabled in the vault. /// @param _disabledDepositAsset List of deposit assets to be disabled in the vault. /// @param _disabledWithdrawalAsset List of withdrawal assets to be disabled in the vault. function setVaultAssets( address[] memory _enabledDepositAsset, address[] memory _enabledWithdrawalAsset, address[] memory _disabledDepositAsset, address[] memory _disabledWithdrawalAsset ) public { require(vaults[msg.sender].created, "Vault not present"); for (uint256 i = 0; i < _enabledDepositAsset.length; i++) { address asset = _enabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; } for (uint256 i = 0; i < _enabledWithdrawalAsset.length; i++) { address asset = _enabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } for (uint256 i = 0; i < _disabledDepositAsset.length; i++) { address asset = _disabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; } for (uint256 i = 0; i < _disabledWithdrawalAsset.length; i++) { address asset = _disabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to get the list of management fee strategies applied to the vault. function getVaultManagementFee() public view returns(address[] memory) { require(vaults[msg.sender].created, "Vault not present"); return managementFeeStrategies[msg.sender].activeManagementFeeList; } /// @dev Function to get the deposit strategy applied to the vault. function getDepositStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].depositStrategy; } /// @dev Function to get the withdrawal strategy applied to the vault. function getWithdrawStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].withdrawStrategy; } /// @dev Function to set the management fee strategies applied to a vault. /// @param _vaultAddress Address of the vault. /// @param _managementFeeAddress Address of the management fee strategy. function setManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender, "Sender not Authorized"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = true; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress] = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length; managementFeeStrategies[_vaultAddress].activeManagementFeeList.push(_managementFeeAddress); } /// @dev Function to deactivate a vault strategy. /// @param _managementFeeAddress Address of the Management Fee Strategy. function removeManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress], "Provided ManagementFee is not active"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender || yieldsterDAO == msg.sender, "Sender not Authorized"); require(platFormManagementFee != _managementFeeAddress || yieldsterDAO == msg.sender,"Platfrom Management only changable by dao!"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = false; if(managementFeeStrategies[_vaultAddress].activeManagementFeeList.length == 1) { managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } else { uint256 index = managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress]; uint256 lastIndex = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length - 1; delete managementFeeStrategies[_vaultAddress].activeManagementFeeList[index]; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]] = index; managementFeeStrategies[_vaultAddress].activeManagementFeeList[index] = managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]; managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } } /// @dev Function to set vault active strategy. /// @param _strategyAddress Address of the strategy. function setVaultActiveStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = true; vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress] = vaultActiveStrategies[msg.sender].activeStrategyList.length; vaultActiveStrategies[msg.sender].activeStrategyList.push(_strategyAddress); } /// @dev Function to deactivate a vault strategy. /// @param _strategyAddress Address of the strategy. function deactivateVaultStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress], "Provided strategy is not active"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = false; if(vaultActiveStrategies[msg.sender].activeStrategyList.length == 1) { vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } else { uint256 index = vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress]; uint256 lastIndex = vaultActiveStrategies[msg.sender].activeStrategyList.length - 1; delete vaultActiveStrategies[msg.sender].activeStrategyList[index]; vaultActiveStrategies[msg.sender].activeStrategyIndex[vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]] = index; vaultActiveStrategies[msg.sender].activeStrategyList[index] = vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]; vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } } /// @dev Function to get vault active strategy. function getVaultActiveStrategy(address _vaultAddress) public view returns(address[] memory) { require(vaults[_vaultAddress].created, "Vault not present"); return vaultActiveStrategies[_vaultAddress].activeStrategyList; } function isStrategyActive(address _vaultAddress, address _strategyAddress) public view returns(bool) { return vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress]; } function getStrategyManagementDetails(address _vaultAddress, address _strategyAddress) public view returns(address, uint256) { require(vaults[_vaultAddress].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress], "Strategy not Active"); return (strategies[_strategyAddress].benefeciary, strategies[_strategyAddress].managementFeePercentage); } /// @dev Function to Manage the vault strategies. /// @param _vaultStrategy Address of the strategy. /// @param _enabledStrategyProtocols List of protocols that are enabled in the strategy. /// @param _disabledStrategyProtocols List of protocols that are disabled in the strategy. /// @param _assetsToBeEnabled List of assets that have to be enabled along with the strategy. function setVaultStrategyAndProtocol( address _vaultStrategy, address[] memory _enabledStrategyProtocols, address[] memory _disabledStrategyProtocols, address[] memory _assetsToBeEnabled ) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_vaultStrategy].created, "Strategy not present"); vaults[msg.sender].vaultEnabledStrategy[_vaultStrategy] = true; for (uint256 i = 0; i < _enabledStrategyProtocols.length; i++) { address protocol = _enabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = true; } for (uint256 i = 0; i < _disabledStrategyProtocols.length; i++) { address protocol = _disabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = false; } for (uint256 i = 0; i < _assetsToBeEnabled.length; i++) { address asset = _assetsToBeEnabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } } /// @dev Function to disable the vault strategies. /// @param _strategyAddress Address of the strategy. /// @param _assetsToBeDisabled List of assets that have to be disabled along with the strategy. function disableVaultStrategy(address _strategyAddress, address[] memory _assetsToBeDisabled) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaults[msg.sender].vaultEnabledStrategy[_strategyAddress], "Strategy was not enabled"); vaults[msg.sender].vaultEnabledStrategy[_strategyAddress] = false; for (uint256 i = 0; i < _assetsToBeDisabled.length; i++) { address asset = _assetsToBeDisabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to set smart strategy applied to the vault. /// @param _smartStrategyAddress Address of the smart strategy. /// @param _type type of smart strategy(deposit or withdraw). function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) public { require(vaults[msg.sender].created, "Vault not present"); require(_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not Supported by Yieldster"); if(_type == 1){ vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if(_type == 2){ vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else{ revert("Invalid type provided"); } } /// @dev Function to check if a particular protocol is enabled in a strategy for a vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. /// @param _protocolAddress Address of the protocol to check. function _isStrategyProtocolEnabled( address _vaultAddress, address _strategyAddress, address _protocolAddress ) public view returns(bool) { if( vaults[_vaultAddress].created && strategies[_strategyAddress].created && protocols[_protocolAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] && vaultStrategyEnabledProtocols[_vaultAddress][_strategyAddress][_protocolAddress]){ return true; } else{ return false; } } /// @dev Function to check if a strategy is enabled for the vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. function _isStrategyEnabled( address _vaultAddress, address _strategyAddress ) public view returns(bool) { if(vaults[_vaultAddress].created && strategies[_strategyAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress]){ return true; } else{ return false; } } /// @dev Function to check if the asset is supported by the vault. /// @param cleanUpAsset Address of the asset. function _isVaultAsset(address cleanUpAsset) public view returns(bool) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].vaultAssets[cleanUpAsset]; } // Assets /// @dev Function to check if an asset is supported by Yieldster. /// @param _address Address of the asset. function _isAssetPresent(address _address) private view returns(bool) { return assets[_address].created; } /// @dev Function to add an asset to the Yieldster. /// @param _symbol Symbol of the asset. /// @param _name Name of the asset. /// @param _tokenAddress Address of the asset. function addAsset( string memory _symbol, string memory _name, address _tokenAddress ) public onlyManager { require(!_isAssetPresent(_tokenAddress),"Asset already present!"); Asset memory newAsset = Asset({name:_name, symbol:_symbol, created:true}); assets[_tokenAddress] = newAsset; } /// @dev Function to remove an asset from the Yieldster. /// @param _tokenAddress Address of the asset. function removeAsset(address _tokenAddress) public onlyManager { require(_isAssetPresent(_tokenAddress),"Asset not present!"); delete assets[_tokenAddress]; } /// @dev Function to check if an asset is supported deposit asset in the vault. /// @param _assetAddress Address of the asset. function isDepositAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultDepositAssets[_assetAddress]; } /// @dev Function to check if an asset is supported withdrawal asset in the vault. /// @param _assetAddress Address of the asset. function isWithdrawalAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultWithdrawalAssets[_assetAddress]; } //Strategies /// @dev Function to check if a strategy is supported by Yieldster. /// @param _address Address of the strategy. function _isStrategyPresent(address _address) private view returns(bool) { return strategies[_address].created; } /// @dev Function to add a strategy to Yieldster. /// @param _strategyName Name of the strategy. /// @param _strategyAddress Address of the strategy. /// @param _strategyAddress List of protocols present in the strategy. /// @param _minter Address of strategy minter. /// @param _executor Address of strategy executor. function addStrategy( string memory _strategyName, address _strategyAddress, address[] memory _strategyProtocols, address _minter, address _executor, address _benefeciary, uint256 _managementFeePercentage ) public onlyManager { require(!_isStrategyPresent(_strategyAddress),"Strategy already present!"); Strategy memory newStrategy = Strategy({ strategyName:_strategyName, created:true, minter:_minter, executor:_executor, benefeciary:_benefeciary, managementFeePercentage: _managementFeePercentage}); strategies[_strategyAddress] = newStrategy; minterStrategyMap[_minter] = _strategyAddress; for (uint256 i = 0; i < _strategyProtocols.length; i++) { address protocol = _strategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); strategies[_strategyAddress].strategyProtocols[protocol] = true; } } /// @dev Function to remove a strategy from Yieldster. /// @param _strategyAddress Address of the strategy. function removeStrategy(address _strategyAddress) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); delete strategies[_strategyAddress]; } /// @dev Function to get strategy executor address. /// @param _strategy Address of the strategy. function strategyExecutor(address _strategy) external view returns(address) { return strategies[_strategy].executor; } /// @dev Function to change executor of strategy. /// @param _strategyAddress Address of the strategy. /// @param _executor Address of the executor. function changeStrategyExecutor(address _strategyAddress, address _executor) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); strategies[_strategyAddress].executor = _executor; } //Smart Strategy /// @dev Function to check if a smart strategy is supported by Yieldster. /// @param _address Address of the smart strategy. function _isSmartStrategyPresent(address _address) private view returns(bool) { return smartStrategies[_address].created; } /// @dev Function to add a smart strategy to Yieldster. /// @param _smartStrategyName Name of the smart strategy. /// @param _smartStrategyAddress Address of the smart strategy. function addSmartStrategy( string memory _smartStrategyName, address _smartStrategyAddress, address _minter, address _executor ) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy already present!"); SmartStrategy memory newSmartStrategy = SmartStrategy ({ smartStrategyName : _smartStrategyName, minter : _minter, executor : _executor, created : true }); smartStrategies[_smartStrategyAddress] = newSmartStrategy; minterStrategyMap[_minter] = _smartStrategyAddress; } /// @dev Function to remove a smart strategy from Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function removeSmartStrategy(address _smartStrategyAddress) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not present"); delete smartStrategies[_smartStrategyAddress]; } /// @dev Function to get ssmart strategy executor address. /// @param _smartStrategy Address of the strategy. function smartStrategyExecutor(address _smartStrategy) external view returns(address) { return smartStrategies[_smartStrategy].executor; } /// @dev Function to change executor of smart strategy. /// @param _smartStrategy Address of the smart strategy. /// @param _executor Address of the executor. function changeSmartStrategyExecutor(address _smartStrategy, address _executor) public onlyManager { require(_isSmartStrategyPresent(_smartStrategy),"Smart Strategy not present!"); smartStrategies[_smartStrategy].executor = _executor; } // Protocols /// @dev Function to check if a protocol is supported by Yieldster. /// @param _address Address of the protocol. function _isProtocolPresent(address _address) private view returns(bool) { return protocols[_address].created; } /// @dev Function to add a protocol to Yieldster. /// @param _symbol symbol of the protocol. /// @param _name Name of the protocol. /// @param _protocolAddress Address of the protocol. function addProtocol( string memory _symbol, string memory _name, address _protocolAddress ) public onlyManager { require(!_isProtocolPresent(_protocolAddress),"Protocol already present!"); Protocol memory newProtocol = Protocol({ name:_name, created:true, symbol:_symbol }); protocols[_protocolAddress] = newProtocol; } /// @dev Function to remove a protocol from Yieldster. /// @param _protocolAddress Address of the protocol. function removeProtocol(address _protocolAddress) public onlyManager { require(_isProtocolPresent(_protocolAddress),"Protocol not present!"); delete protocols[_protocolAddress]; } }
Smart Strategy @dev Function to check if a smart strategy is supported by Yieldster. @param _address Address of the smart strategy.
function _isSmartStrategyPresent(address _address) private view returns(bool) { return smartStrategies[_address].created; }
5,938,244
[ 1, 23824, 19736, 225, 4284, 358, 866, 309, 279, 13706, 6252, 353, 3260, 635, 31666, 8190, 18, 225, 389, 2867, 5267, 434, 326, 13706, 6252, 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 ]
[ 1, 1, 1, 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, 389, 291, 23824, 4525, 6351, 12, 2867, 389, 2867, 13, 7010, 3639, 3238, 7010, 3639, 1476, 7010, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 327, 13706, 1585, 15127, 63, 67, 2867, 8009, 4824, 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 ]
./partial_match/4/0x3e7c0Ad633323FC49801c57D56a7A2b75a23164F/sources/StakingPool.sol
* @dev Returns the addresses that each personal stake was created for by an address @param _address address that created the stakes @return address[] array of amounts/
function getPersonalStakeForAddresses(address _address) external view returns (address[] memory) { address[] memory stakedFor; (, , stakedFor) = getPersonalStakes(_address); return stakedFor; }
8,667,094
[ 1, 1356, 326, 6138, 716, 1517, 17816, 384, 911, 1703, 2522, 364, 635, 392, 1758, 225, 389, 2867, 1758, 716, 2522, 326, 384, 3223, 327, 1758, 8526, 526, 434, 30980, 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, 565, 445, 29936, 287, 510, 911, 1290, 7148, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 1758, 8526, 3778, 384, 9477, 1290, 31, 203, 3639, 261, 16, 269, 384, 9477, 1290, 13, 273, 29936, 287, 510, 3223, 24899, 2867, 1769, 203, 203, 3639, 327, 384, 9477, 1290, 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 ]
./partial_match/1/0xD42a2bB59775694c9Df4c7822BfFAb150e6c699D/sources/src/PRBProxyRegistry.sol
@inheritdoc IPRBProxyRegistry
function deployAndExecute( address target, bytes calldata data ) external override noProxy(msg.sender) returns (IPRBProxy proxy) { }
15,704,789
[ 1, 36, 10093, 2971, 19437, 3886, 4243, 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, 7286, 1876, 5289, 12, 203, 3639, 1758, 1018, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1158, 3886, 12, 3576, 18, 15330, 13, 203, 3639, 1135, 261, 2579, 19437, 3886, 2889, 13, 203, 565, 288, 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 ]
./partial_match/1/0xe072658111387BD922c4AC41dBe4dd6BF7D26fFB/sources/Jinsamo.sol
Set the name for display purposes
name = "Jinsamo";
3,946,462
[ 1, 694, 326, 508, 364, 2562, 13694, 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, 3639, 508, 273, 315, 46, 2679, 301, 83, 14432, 4766, 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 ]